Python Remove last 3 characters of a string


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 space and convert to upper-case

an example would be:

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

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

examples of foo could be:


The string could be 6 or 7 characters and I need to drop the last 3 (assuming no white space)

Any tips?

11/25/2009 5:19:34 PM

Accepted Answer

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()
11/25/2009 5:23:17 PM

It doesn't work as you expect because strip is character based. You need to do this instead:

foo = foo.replace(' ', '')[:-3].upper()

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow