Python string replace first

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 first occurrence of a substring in Python

In this article, we will discuss different ways to replace the first occurrence of a substring from a string in Python.

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

In this string, the substring “is” occurs at 3 different places. But we want to replace only the first occurrence of substring “is” with “XX”. After replacement, the final string should be like,

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

There are different ways to replace only the first occurrence of a substring in string. Let’s discuss them one by one.

Using replace() function

In Python, the string class provides a function replace() to change the content of a string. It’s syntax is as follows,

Frequently Asked:

replace(substring, replacement, count)
  • substring: The substring that need to be replaced in the string.
  • replacement: The replacement string. By which the substring will be replaced.
  • count: The maximumn number of occurrences to replace.

It replaces the count number of occurrences of given substring with the replacement string. A string is immutable in Python, therefore the replace() function returns a copy of the string with modified content.

To replace only first occurrence of “is” with “XX”, pass the count value as 1.

For example:

strValue = "This is the last rain of Season and Jack is here." # Replace first occurrence of substring 'is' with 'XX' in the string strValue = strValue.replace('is', 'XX', 1) print(strValue)
ThXX is the last rain of Season and Jack is here.

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

Using Regex

The regex module in Python provides a function sub() to replace the contents of a string based on a matching regex pattern. The signature of function is like this,

sub(pattern, replacement_str, original_str, count=N)

It looks for the matches of the given regex pattern in the sting original_str and replaces N occurrences of substrings that matches with the replacement string i.e. replacement_str.

We can use this to replace only first occurrence of “is” with “XX”. For that we need to pass the count parameter as 1.

For example:

import re strValue = "This is the last rain of season and Jack is here." # Replace first occurrence of substring 'is' with 'XX' in the string strValue = re.sub('is', 'XX', strValue, count=1 ) print(strValue)
ThXX is the last rain of Season and Jack is here.

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

We learned about two different ways to replace this first occurrence of a substring in a string in Python.

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

Читайте также:  Python str format number
Оцените статью