Python str replace last

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.

Источник

Python str replace last

Last updated: Feb 21, 2023
Reading time · 5 min

banner

# Table of Contents

# Replace the Last occurrence of Substring in String in Python

To replace the last occurrence of a substring in a string:

  1. Use the str.rsplit() method to split the string on the substring, once, from the right.
  2. Use the str.join() method to join the list with the replacement string as the separator.
Copied!
my_str = 'one two two' def replace_last(string, old, new): return new.join(string.rsplit(old, 1)) # 👇️ one two three print(replace_last(my_str, 'two', 'three')) new_str = 'three'.join(my_str.rsplit('two', 1)) print(new_str) # 👉️ one two three

The first step is to use the str.rsplit() method to split the string into a list, once, from the right.

Copied!
my_str = 'one two two' # 👇️ ['one two ', ''] print(my_str.rsplit('two', 1))

The str.rsplit method returns a list of the words in the string using the provided separator as the delimiter string.

Copied!
my_str = 'bobby hadz com' print(my_str.rsplit(' ')) # 👉️ ['bobby', 'hadz', 'com'] print(my_str.rsplit(' ', 1)) # 👉️ ['bobby hadz', 'com']

The method takes the following 2 arguments:

Name Description
separator Split the string into substrings on each occurrence of the separator
maxsplit At most maxsplit splits are done, the rightmost ones (optional)

Except for splitting from the right, rsplit() behaves like split() .

The last step is to use the str.join() method to join the list into a string with the replacement as the separator.

Copied!
my_str = 'one two two' new_str = 'three'.join(my_str.rsplit('two', 1)) print(new_str) # 👉️ one two three

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

The string the method is called on is used as the separator between the elements.

If the substring is not found in the string, the string is returned as is.

Copied!
my_str = 'bobbyhadz.com' new_str = 'three'.join(my_str.rsplit('two', 1)) print(new_str) # 👉️ bobbyhadz.com

Alternatively, you can use the str.rfind() method.

# Replace Last occurrence of Substring in String using rfind()

This is a two-step process:

  1. Use the str.rfind() method to get the index of the last occurrence of the substring.
  2. Use string slicing to replace the last occurrence of the substring in the string.
Copied!
def replace_last(string, old, new): if old not in string: return string index = string.rfind(old) return string[:index] + new + string[index+len(old):] # 👇️ one two three print(replace_last('one two two', 'two', 'three')) # 👇️ 'abc _ 123' print(replace_last('abc abc 123', 'abc', '_'))

We first check if the substring is not found in the string, in which case we return the string as is.

We used the str.rfind() method to get the index of the last occurrence of the substring in the string.

The str.rfind method returns the highest index in the string where the provided substring is found.

Copied!
print('abc abc 123'.rfind('abc')) # 👉️ 4

The method returns -1 if the substring is not contained in the string.

The slice string[:index] starts at index 0 and goes up to, but not including the index of the last occurrence of the substring.

Copied!
def replace_last(string, old, new): if old not in string: return string index = string.rfind(old) return string[:index] + new + string[index+len(old):] # 👇️ one two three print(replace_last('one two two', 'two', 'three')) # 👇️ 'abc _ 123' print(replace_last('abc abc 123', 'abc', '_'))

We then use the addition (+) operator to append the replacement string.

The slice string[index+len(old):] starts at the index after the last character of the substring to be replaced.

If the substring is not contained in the string, we return the string as is.

Copied!
def replace_last(string, old, new): if old not in string: return string index = string.rfind(old) return string[:index] + new + string[index+len(old) - 1:] # 👇️ bobbyhadz.com print(replace_last('bobbyhadz.com', 'two', 'three'))

# Replace Nth occurrence of Substring in String in Python

To replace the Nth occurrence of a substring in a string:

  1. Find the index of the Nth occurrence of the substring in the string.
  2. Use string slicing to replace the Nth occurrence of the substring.
  3. If the substring is not contained N times in the string, return the string as is.
Copied!
def replace_nth(string, old, new, n): index_of_occurrence = string.find(old) occurrence = int(index_of_occurrence != -1) print(occurrence) # 👇️ find index of Nth occurrence while index_of_occurrence != -1 and occurrence != n: index_of_occurrence = string.find(old, index_of_occurrence + 1) occurrence += 1 # 👇️ index of Nth occurrence found, replace substring if occurrence == n: return ( string[:index_of_occurrence] + new + string[index_of_occurrence+len(old):] ) # 👇️ if N occurrences of substring not found in string, return string return string my_str = 'one one one two' new_str = replace_nth(my_str, 'one', '_', 1) print(new_str) # 👉️ _ one one two new_str = replace_nth(my_str, 'one', '_', 2) print(new_str) # 👉️ one _ one two new_str = replace_nth(my_str, 'one', '_', 3) print(new_str) # 👉️ one one _ two new_str = replace_nth(my_str, 'one', '_', 100) print(new_str) # 👉️ one one one two new_str = replace_nth(my_str, 'abc', '_', 100) print(new_str) # 👉️ one one one two

We used the str.find() method to find the index of the first occurrence of the substring in the string.

The str.find method returns the index of the first occurrence of the provided substring in the string.

Источник

Читайте также:  Jquery input post php
Оцените статью