Python replace last string

Python replace string

Python replace string tutorial shows how to replace strings in Python.

  • replace method
  • re.sub method
  • translate method
  • string slicing and formatting

Python replace string with replace method

The replace method return a copys of the string with all occurrences of substring old replaced by new.

  • old − old substring to be replaced
  • new − new substring to replace old substring.
  • count − the optional count argument determines how many occurrences are replaced
#!/usr/bin/python msg = "There is a fox in the forest. The fox has red fur." msg2 = msg.replace('fox', 'wolf') print(msg2)

In the example, both occurrences of word ‘fox’ are replaced with ‘wolf’.

$ ./replacing.py There is a wolf in the forest. The wolf has red fur.

Alternatively, we can use the str.replace method. It takes the string on which we do replacement as the first parameter.

#!/usr/bin/python msg = "There is a fox in the forest. The fox has red fur." msg2 = str.replace(msg, 'fox', 'wolf') print(msg2)

The example is equivalent to the previous one.

In the next example, we have a CSV string.

#!/usr/bin/python data = "1,2,3,4,5,6,7,8,9,10" data2 = data.replace(',', '\n') print(data2)

The replace each comma with a newline character.

$ ./replacing3.py 1 2 3 4 5 6 7 8 9 10 $ ./replacing3.py | awk ' < sum+=$1>END ' 55

Python replace first occurrence of string

The count parameter can be used to replace only the first occurrence of the given word.

#!/usr/bin/python msg = "There is a fox in the forest. The fox has red fur." msg2 = msg.replace('fox', 'wolf', 1) print(msg2)

The example replaces the first occurrence of the word ‘fox’.

$ ./replace_first.py There is a wolf in the forest. The fox has red fur.

Python replace last occurrence of string

In the next example, we replace the last occurrence of word ‘fox’.

#!/usr/bin/python msg = "There is a fox in the forest. The fox has red fur." oword = 'fox' nword = 'wolf' n = len(nword) idx = msg.rfind(oword) idx2 = idx + n - 1 print(f'')

We find the index of the last ‘fox’ word present in the message utilizing rfind method. We build a new string by omitting the old word an placing a new word there instead. We use string slicing and formatting operations.

$ ./replace_last.py There is a fox in the forest. The wolf has red fur.

Python chaining of replace methods

It is possible to chain the replace methods to do multiple replacements.

#!/usr/bin/python msg = "There is a fox in the forest. The fox has red fur." msg2 = msg.replace('fox', 'wolf').replace('red', 'brown').replace('fur', 'legs') print(msg2)

In the example, we perform three replacements.

$ ./chaining.py There is a wolf in the forest. The wolf has brown legs.

Python replace characters with translate

The translate method allows to replace multiple characters specified in the dictionary.

#!/usr/bin/python msg = "There is a fox in the forest. The fox has red fur." print(msg.translate(str.maketrans()))

We replace the dot characters with the exclamation marks in the example.

$ ./translating.py There is a fox in the forest! The fox has red fur!

Python replace string with re.sub

We can use regular expressions to replace strings.

re.sub(pattern, repl, string, count=0, flags=0)

The re.sub method returns the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl.

The Battle of Thermopylae was fought between an alliance of Greek city-states, led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over the course of three days, during the second Persian invasion of Greece.

We have a small text file.

#!/usr/bin/python import re filename = 'thermopylae.txt' with open(filename) as f: text = f.read() cleaned = re.sub('[\.,]', '', text) words = set(cleaned.split()) for word in words: print(word)

We read the text file and use the re.sub method to remove the punctunation characters. We split the text into words and use the set function to get unique words.

In our case, we only have a dot and comma punctunation characters in the file. We replace them with empty string thus removing them.

$ ./replace_reg.py city-states days was Empire and second of led Battle alliance Greece King Persian Leonidas during between course Thermopylae Sparta I over three by Xerxes invasion an Greek The fought the

In this tutorial we have replaced strings in Python.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

Источник

Replace Last occurrence of a String in Python

This article will discuss different ways to replace only the last occurrence of a substring in a string.

Table Of Contents

"This is the last rain of Season and Jack is here."

We want to replace the last occurrence of “is” with the “XX”. The final string should be like,

"This is the last rain of Season and Jack XX here."

There are different ways to do this. Let’s discuss them one by one.

Frequently Asked:

Using replace() function.

In Python, the string class provides a function replace(), and it helps to replace all the occurrences of a substring with another substring. We can use that to replace only the last occurrence of a substring in a string.

  • Reverse the string to be replaced.
  • Reverse the replacement string.
  • Reverse the original string and replace the first occurrence of reversed substring * with the reversed replacement string.
  • Then reverse the modified string and assign it back to the original string.

Basically, if we reverse the original string and the substring to be replaced, we need to remove its first occurrence instead of the last. For that, pass the max count as 1 in the replace() function. Then, in the end, we can reverse the modified string again.

For example,

strValue = "This is the last rain of Season and Jack is here." strToReplace = 'is' replacementStr = 'XX' # Reverse the substring that need to be replaced strToReplaceReversed = strToReplace[::-1] # Reverse the replacement substring replacementStrReversed = replacementStr[::-1] # Replace last occurrences of substring 'is' in string with 'XX' strValue = strValue[::-1].replace(strToReplaceReversed, replacementStrReversed, 1)[::-1] print(strValue)
This is the last rain of Season and Jack XX here.

It replaced only the last occurrence of “is” with the “XX” in the string.

Using rfind() function

Search for the index position of the last occurrence of the substring that needs to be replaced from the original string. For that, use the rfind() function of the string class. It returns the highest index of the substring in the string i.e., the index position of the last occurrence of the substring. Then using the subscript operator and index range, replace that last occurrence of substring.

Basically, select all the characters before the last occurrence of substring “is” and then add “XX” to it. Then select all the characters after the last occurrence of the substring “is” and append it to the end of the new string.

For example,

strValue = "This is the last rain of season and Jack is here." strToReplace = 'is' replacementStr = 'XX' # Search for the last occurrence of substring in string pos= strValue.rfind(strToReplace) if pos > -1: # Replace last occurrences of substring 'is' in string with 'XX' strValue = strValue[:pos] + replacementStr + strValue[pos + len(strToReplace): ] print(strValue)
This is the last rain of Season and Jack XX here.

It replaced only the last occurrence of “is” with the “XX” in the string.

Using rsplit() and join()

To replace the last occurrence of a substring from a string, split the string from right using substring as delimiter and keep the maximum count of splits as 1. It will give us a list with two strings i.e.

  • A string containing all the characters before the delimiter substring.
  • A string containing all the characters after the delimiter substring.

Then join these using join() function and use the replacement string as delimiter.

For example,

strValue = "This is the last rain of season and Jack is here." # Substring that need to be replaced strToReplace = 'is' # Replacement substring replacementStr = 'XX' # Replace last occurrences of substring 'is' in string with 'XX' strValue = replacementStr.join(strValue.rsplit(strToReplace, 1)) print(strValue)
This is the last rain of Season and Jack XX here.

It replaced only the last occurrence of “is” with the “XX” in the string.

We learned about three different ways to replace the last occurrence of a string in Python.

Источник

Читайте также:  Docker nginx php fpm mysql phpmyadmin
Оцените статью