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
split
slice
concentrate
This is a good workout for beginners and it's easy to achieve.
Another advanced method is a function like this:
def trim(s):
return trim(s[slice])
And for this question, you just want to remove the last characters, so you can write like this:
def trim(s):
return s[ : -3]
I think you are over to care about what those three characters are, so you lost. You just want to remove last three, nevertheless who they are!
If you want to remove some specific characters, you can add some if judgements:
def trim(s):
if [conditions]: ### for some cases, I recommend using isinstance().
return trim(s[slice])
Aren't you performing the operations in the wrong order? You requirement seems to be foo[:-3].replace(" ", "").upper()
It doesn't work as you expect because strip is character based. You need to do this instead:
foo = foo.replace(' ', '')[:-3].upper()
I try to avoid regular expressions, but this appears to work:
string = re.sub("\s","",(string.lower()))[:-3]