214

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

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Sam Machin
  • 3,063
  • 5
  • 20
  • 18
  • 1
    This question is confusing. The title asks for removing the last 3 characters of a string, but the first example removes 4 characters and there seem to be more requirements than just removing a given number of characters (like also stripping whitespace). – mkrieger1 Jul 14 '22 at 09:54
  • 1
    @mkrieger1 The accepted answer appears to answer four completely different questions, implying that this was originally a chameleon question. We also have a much better canonical for the task of removing a suffix from a string - https://stackoverflow.com/questions/1038824/how-do-i-remove-a-substring-from-the-end-of-a-string - and unconditionally removing the last few characters is a simple matter of slicing, which is also very well covered by canonicals. I think this question is not useful to the site at all, despite the attention it has garnered over the years. – Karl Knechtel Aug 19 '22 at 03:13

10 Answers10

403

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()
Noctis Skytower
  • 21,433
  • 16
  • 79
  • 117
  • 11
    I would like to note that `''.join(foo.split())` is better than `foo.replace(' ', '')`, when used on unicode strings because it removes any *whitespace* character, in addition to the `' '` character (in particular, non-breaking spaces are also removed). That said `replace()` is probably much faster, so it can be used if, say, the input strings are known to be encoded in ASCII, which only has one space character (I'm using Python 2 terminology, here.) – Eric O. Lebigot Mar 14 '13 at 01:33
95

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

foo = foo.replace(' ', '')[:-3].upper()
Nadia Alramli
  • 111,714
  • 37
  • 173
  • 152
23
>>> foo = "Bs12 3ab"
>>> foo[:-3]
'Bs12 '
>>> foo[:-3].strip()
'Bs12'
>>> foo[:-3].strip().replace(" ","")
'Bs12'
>>> foo[:-3].strip().replace(" ","").upper()
'BS12'
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
9

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)

Mattias Nilsson
  • 3,639
  • 1
  • 22
  • 29
5
  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])
Jaylin
  • 79
  • 1
  • 4
4
>>> foo = 'BS1 1AB'
>>> foo.replace(" ", "").rstrip()[:-3].upper()
'BS1'
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
4

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

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

krs1
  • 1,125
  • 7
  • 16
1

What's wrong with this?

foo.replace(" ", "")[:-3].upper()
abyx
  • 69,862
  • 18
  • 95
  • 117
0

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

AndreaG
  • 1,106
  • 2
  • 12
  • 28
0

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")
Lee Joramo
  • 56
  • 1
  • 5