I\'m 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 white
It some what depends on your definition of whitespace. I would generally call whitespace to be spaces, tabs, line breaks and carriage returns. If this is your definition you want to use a regex with \s to replace all whitespace charactors:
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")
>>> foo = "Bs12 3ab"
>>> foo[:-3]
'Bs12 '
>>> foo[:-3].strip()
'Bs12'
>>> foo[:-3].strip().replace(" ","")
'Bs12'
>>> foo[:-3].strip().replace(" ","").upper()
'BS12'
Removing any and all whitespace:
foo = ''.join(foo.split())
Removing last three characters:
foo = foo[:-3]
Converting to capital letters:
foo = foo.upper()
All of that code in one line:
foo = ''.join(foo.split())[:-3].upper()
What's wrong with this?
foo.replace(" ", "")[:-3].upper()
You might have misunderstood rstrip slightly, it strips not a string but any character in the string you specify.
Like this:
>>> text = "xxxxcbaabc"
>>> text.rstrip("abc")
'xxxx'
So instead, just use
text = text[:-3]
(after replacing whitespace with nothing)
>>> foo = 'BS1 1AB'
>>> foo.replace(" ", "").rstrip()[:-3].upper()
'BS1'