Replace last 2 characters python

  • Problem Formulation
  • Method 1: rfind[]
  • Method 2: Regex sub[]
  • Python Regex Course

Problem Formulation

Given a string, a substring, and a replacement string in Python.

  • String s
  • Substring sub
  • Replacement string repl

How to find and replace the last occurrence of sub with the replacement repl in the Python string s?

Let’s have a look at a couple of examples to thoroughly understand the problem:

Example 1:
s = 'fifi'
sub = 'fi'
repl = 'nxter'
result: 'finxter'

Example 2:
s = '...'
sub = '.'
repl = 'hello'
result: '..hello'

Example 3:
s = 'hello\nworld\nuniverse'
sub = '\n'
repl = ' and '
result: 'hello\nworld and universe'

Let’s dive into the first pure Python method next!

Method 1: rfind[]

The Python string.rfind[substr] method returns the highest index in the string where a substring is found, i.e., the index of the last occurrence of the substring in a given string or -1 if not found. You can use slicing in combination with the found index to solve the problem like so:

index = s.rfind[sub]
s[:index] + repl + s[index+len[sub]:]
  • You use s.rfind[sub] to find the last occurrence of sub in s.
  • You use slicing operations s[:index] and s[index+len[sub]:] to obtain the unchanged parts of the new string that are not replaced.
  • You insert the replacement string repl using string concatenation with the results of the above slicing operations.

Let’s have a look at a practical example next!

Example: Here’s how you can create a new string with the last occurrence of a given substring replaced by a given replacement string:

def repl_last[s, sub, repl]:
    index = s.rfind[sub]
    if index == -1:
        return s
    return s[:index] + repl + s[index+len[sub]:]


# Example 1:
s = 'fifi'
sub = 'fi'
repl = 'nxter'
result = repl_last[s, sub, repl]
print[result]
# result: 'finxter'

For comprehensibility, let’s dive into the other two examples introduced in the problem formulation:

# Example 2:
s = '...'
sub = '.'
repl = 'hello'
result = repl_last[s, sub, repl]
print[result]
# result: '..hello'


# Example 3:
s = 'hello\nworld\nuniverse'
sub = '\n'
repl = ' and '
result = repl_last[s, sub, repl]
print[result]
# result: 'hello\nworld and universe'

You can find some background information on rfind[] and multiple other string methods in the following video—conquer string methods once and for all! 🙂

Python String Methods [Ultimate Guide]

Method 2: Regex sub[]

The regex function re.sub[P, R, S] replaces all occurrences of the pattern P with the replacement R in string S. It returns a new string.

For example, if you call re.sub['a', 'b', 'aabb'], the result will be the new string 'bbbb' with all characters 'a' replaced by 'b'.

However, you don’t want to replace all matching substrings—only the last one. So, how to accomplish that?

Let’s have a look at the short answer—I’ll explain it in more detail and with an example afterwards:

pattern = sub + '[?!.*' + sub + ']'
return re.sub[pattern, repl, s, flags=re.DOTALL]
  • You create the pattern sub with the negative lookahead [?!.*sub] to make sure that we match the right-most pattern sub and it does not occur anywhere on the right.
  • You replace this rightmost pattern with the replacement string using the re.sub[] method.
  • You set the re.DOTALL flag to make sure that the dot and asterisk .* part of the pattern matches all characters including the newline character. This is only a minor optimization to correctly match a couple of border cases.

Okay, let’s have a look at the code to see if it correctly solves our problem!

import re


def repl_last[s, sub, repl]:
    pattern = sub + '[?!.*' + sub + ']'
    return re.sub[pattern, repl, s, flags=re.DOTALL]


# Example 1:
s = 'fifi'
sub = 'fi'
repl = 'nxter'
result = repl_last[s, sub, repl]
print[result]
# result: 'finxter'


# Example 2:
s = '...'
sub = '.'
repl = 'hello'
result = repl_last[s, sub, repl]
print[result]
# result: '..hello'


# Example 3:
s = 'hello\nworld\nuniverse'
sub = '\n'
repl = ' and '
result = repl_last[s, sub, repl]
print[result]
# result: 'hello\nworld and universe'

It does! Regex to the rescue!

Do you want to master the regex superpower? Check out my new book The Smartest Way to Learn Regular Expressions in Python with the innovative 3-step approach for active learning: [1] study a book chapter, [2] solve a code puzzle, and [3] watch an educational chapter video.

Related Tutorial:

  • Python Regex Sub

Python Regex Sub - How to Replace a Pattern in a String?

Python Regex Course

Google engineers are regular expression masters. The Google search engine is a massive text-processing engine that extracts value from trillions of webpages.  

Facebook engineers are regular expression masters. Social networks like Facebook, WhatsApp, and Instagram connect humans via text messages. 

Amazon engineers are regular expression masters. Ecommerce giants ship products based on textual product descriptions.  Regular expressions ​rule the game ​when text processing ​meets computer science. 

If you want to become a regular expression master too, check out the most comprehensive Python regex course on the planet:

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners [NoStarch 2020], coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

How do I change the last two characters of a string in Python?

To replace the last N characters in a string using indexing, select all characters of string except the last n characters i.e. str[:-n]. Then add replacement substring after these selected characters and assign it back to the original variable.

How do you cut the last two characters in Python?

Use slice notation [length-2:] to Get the last two characters of string Python. For it, you have to get the length of string and minus 2 char.

How do I remove the last 3 characters from a string in Python?

In python, we can select characters in a string using negative indexing too. Last character in string has index -1 and it will keep on decreasing till we reach the start of the string. So to remove last 3 characters from a string select character from 0 i.e. to -3 i.e.

How do I change the end of a string in Python?

replace[] Return Value The replace[] method returns a copy of the string where the old substring is replaced with the new substring. The original string is unchanged. If the old substring is not found, it returns the copy of the original string.

Bài mới nhất

Chủ Đề