How do i change the last 3 characters of a string in python?

In this article, we would like to show you how to replace last 3 characters in string in Python.

Quick solution:

text = "ABCD"

size = len(text)     # text length
replacement = "XYZ"  # replace with this

text = text.replace(text[size - 3:], replacement)

print(text)  # AXYZ

Practical example

In this example, we use replace() method to replace last 3 characters in text string.

text = "ABCD"

print("String before:", text)

size = len(text)     # text length
replacement = "XYZ"  # replace with this

text = text.replace(text[size - 3:], replacement)

print("String after: ", text)  # AXYZ

Output:

String before: ABCD
String after:  AXYZ

Note:

Number of characters to replace (3) and number of characters in replacement don't have to be the same.

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

How do i change the last 3 characters of a string in python?

mkrieger1

15.7k4 gold badges46 silver badges57 bronze badges

asked Nov 25, 2009 at 17:14

2

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

answered Nov 25, 2009 at 17:23

Noctis SkytowerNoctis Skytower

20.7k16 gold badges78 silver badges112 bronze badges

1

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

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

answered Nov 25, 2009 at 17:17

Nadia AlramliNadia Alramli

108k35 gold badges170 silver badges151 bronze badges

1

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

answered Nov 26, 2009 at 1:15

ghostdog74ghostdog74

314k55 gold badges252 silver badges339 bronze badges

2

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)

answered Nov 25, 2009 at 17:22

Mattias NilssonMattias Nilsson

3,5741 gold badge23 silver badges28 bronze badges

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

answered Nov 25, 2009 at 17:18

SilentGhostSilentGhost

294k64 gold badges301 silver badges291 bronze badges

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

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

answered Nov 25, 2009 at 17:29

krs1krs1

1,1057 silver badges16 bronze badges

2

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

answered Nov 28, 2018 at 1:50

What's wrong with this?

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

answered Nov 25, 2009 at 17:18

abyxabyx

67.1k18 gold badges91 silver badges116 bronze badges

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

answered Nov 25, 2009 at 17:26

How do i change the last 3 characters of a string in python?

AndreaGAndreaG

1,0962 gold badges12 silver badges27 bronze badges

1

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

answered Nov 25, 2009 at 17:33

How do you change the last character of a string in Python?

To replace only the last character in a string, we will pass the regex pattern “. $” and replacement character in sub() function. This regex pattern will match only the last character in the string and that will be replaced by the given character.

How do you cut the last 3 characters in Python?

# Get last character of string i.e. char at index position -1. last_char = sample_str[-1] ... .
# get the length of string. length = len(sample_str) ... .
sample_str = "Sample String" # Get last 3 character. ... .
# get the length of string. length = len(sample_str) ... .
**** Get last character of a String in python **** Last character : g..

How do you trim the last 4 characters of a string in Python?

5 Ways to Remove the Last Character From String in Python.
Using Positive index by slicing..
Using Negative Index by Slicing..
Using the rstrip function to Remove Last Character From String in Python..
Using for loop to Remove Last Character From String in Python..
Using regex function..

How do I get the last 5 characters of a string in Python?

Getting the last n characters To access the last n characters of a string in Python, we can use the subscript syntax [ ] by passing -n: as an argument to it. -n is the number of characters we need to extract from the end position of a string.