Python Remove last 3 characters of a string

PythonString

Python Problem Overview


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:

BS1 1AB
bs11ab
BS111ab

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

Any tips?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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

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

Solution 3 - Python

>>> foo = "Bs12 3ab"
>>> foo[:-3]
'Bs12 '
>>> foo[:-3].strip()
'Bs12'
>>> foo[:-3].strip().replace(" ","")
'Bs12'
>>> foo[:-3].strip().replace(" ","").upper()
'BS12'

Solution 4 - Python

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)

Solution 5 - Python

>>> foo = 'BS1 1AB'
>>> foo.replace(" ", "").rstrip()[:-3].upper()
'BS1'

Solution 6 - Python

I try to avoid regular expressions, but this appears to work:

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

Solution 7 - Python

  1. split
  2. slice
  3. 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])

Solution 8 - Python

What's wrong with this?

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

Solution 9 - Python

Aren't you performing the operations in the wrong order? You requirement seems to be foo[:-3].replace(" ", "").upper()

Solution 10 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSam MachinView Question on Stackoverflow
Solution 1 - PythonNoctis SkytowerView Answer on Stackoverflow
Solution 2 - PythonNadia AlramliView Answer on Stackoverflow
Solution 3 - Pythonghostdog74View Answer on Stackoverflow
Solution 4 - PythonMattias NilssonView Answer on Stackoverflow
Solution 5 - PythonSilentGhostView Answer on Stackoverflow
Solution 6 - Pythonkrs1View Answer on Stackoverflow
Solution 7 - PythonJaylinView Answer on Stackoverflow
Solution 8 - PythonabyxView Answer on Stackoverflow
Solution 9 - PythonAndreaGView Answer on Stackoverflow
Solution 10 - PythonLee JoramoView Answer on Stackoverflow