Fix Python – Remove last 3 characters of a string

Question

Asked By – Sam Machin

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 lose both, e.g. if foo = "BS11 1AA" I just get "BS".

Examples of foo could be:

BS1 1AB
bs11ab
BS111ab

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

Now we will see solution for issue: Remove last 3 characters of a string


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()

This question is answered By – Noctis Skytower

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0