remove last occurrence of character in string

Python – Remove Last Occurrence of Character in String

In this tutorial, we will look at how to remove the last occurrence of a character from a string in Python with the help of some examples.

remove last occurrence of character in string

Strings are immutable in Python. That is, they cannot be modified after they are created. You can, however, create a copy of the original string with the last occurrence of the character removed.

Use the following steps –

  1. Find the index of the last occurrence of the character in the string.
    • For this, first, reverse the string and find the first index of the character in the reversed string.
    • Then, subtract this index and one from the length of the string to get the last index of the character in the original string.
  2. Then, use the above index to slice the original string such that the character at that index is skipped.

Let’s look at an example –

# create a string
s = "not me, not her"
# get index of last occurrence of 'n'
rev_s = s[::-1]
i = len(s) - rev_s.index('n') - 1
# remove the character at index i in s
print(s[:i]+s[i+1:])

Output:

not me, ot her

You can see that the output string does not contain the last occurrence of the character ‘n’ from the original string. Also, notice that the other occurrences of the character ‘n’ in the string are unaffected.

For more on the Python string index() function, refer to its documentation.

Alternatively, you can also use a loop to iterate through the characters of the original string from the right and remove the last occurrence of a character from a string in Python. Use the following steps –

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

  1. Create an empty string to store our result and a flag set to False to determine whether we have encountered the character that we want to remove.
  2. Iterate through each character in the string from the right.
  3. For each character, check if it’s equal to the character we want to remove and whether the flag is False. If both the conditions are true, set the flag to True and skip over to the next iteration. Else, add the character to our result string.
  4. Reverse the result string to get our original string with the last instance of the character removed.

Let’s look at an example –

# create a string
s = "not me, not her"

result = ""
ch_to_remove = 'n'
occurred_flag = False

# iterate over each character in s from right
for ch in s[::-1]:
    if ch == ch_to_remove and occurred_flag == False:
        occurred_flag = True
        continue
    else:
        result += ch

# reverse the result
result = result[::-1]
# display the resulting string
print(result)

Output:

not me, ot her

We get the same result as above. The resulting string has the last instance of the character removed. Note that this method is too lengthy as compared to the previous method.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top