Python Delete last 3 characters of string

I am trying to remove the last 3 characters from a string in python, I donโ€™t know what these characters are, so I canโ€™t use rstrip , I also need to remove any space and convert to the upper case

example:

 foo = "Bs12 3ab" foo.replace(" ", "").rstrip(foo[-3:]).upper() 

This works and gives me BS12, which I want, however, if the last 4th and 3rd characters are the same, I lose both, for example, if foo = "BS11 1AA" I just get 'BS'

Examples of foo might be:

 BS1 1AB bs11ab BS111ab 

The string can be 6 or 7 characters and I need to discard the last 3 (no spaces)

Any tips?

+74
python string
Nov 25 '09 at 17:14
source share
9 answers

It does not work as you expect, because the strip has a character. You need to do this instead:

 foo = foo.replace(' ', '')[:-3].upper() 
+83
Nov 25 '09 at 17:17
source share

Delete all spaces:

 foo = ''.join(foo.split()) 

Delete the last three characters:

 foo = foo[:-3] 

Uppercase conversion:

 foo = foo.upper() 

All this code in one line:

 foo = ''.join(foo.split())[:-3].upper() 
+124
Nov 25 '09 at 17:23
source share
 >>> foo = "Bs12 3ab" >>> foo[:-3] 'Bs12 ' >>> foo[:-3].strip() 'Bs12' >>> foo[:-3].strip().replace(" ","") 'Bs12' >>> foo[:-3].strip().replace(" ","").upper() 'BS12' 
+12
Nov 26 '09 at 1:15
source share

Perhaps you misunderstood rstrip, it does not contain a string, but any character in the specified string.

Like this:

 >>> text = "xxxxcbaabc" >>> text.rstrip("abc") 'xxxx' 

So instead just use

 text = text[:-3] 

(after replacing the space with nothing)

+5
Nov 25 '09 at 17:22
source share

What happened to that?

 foo.replace(" ", "")[:-3].upper() 
+1
Nov 25 '09 at 17:18
source share
 >>> foo = 'BS1 1AB' >>> foo.replace(" ", "").rstrip()[:-3].upper() 'BS1' 
+1
Nov 25 '09 at 17:18
source share

I am trying to avoid regular expressions, but this works:

string = re.sub("\s","",(string.lower()))[:-3]

+1
Nov 25 '09 at 17:29
source share

Are you performing operations in the wrong order? The requirement, in your foo[:-3].replace(" ", "").upper() , is foo[:-3].replace(" ", "").upper()

0
Nov 25 '09 at 17:26
source share

It depends on your definition of spaces. I would usually call spaces with spaces, tabs, line breaks and carriage returns. If this is your definition, you want to use the regex with \ s to replace all space characters:

 import re def myCleaner(foo): print 'dirty: ', foo foo = re.sub(r'\s', '', foo) foo = foo[:-3] foo = foo.upper() print 'clean:', foo print myCleaner("BS1 1AB") myCleaner("bs11ab") myCleaner("BS111ab") 
0
Nov 25 '09 at 17:33
source share



All Articles