- How to replace all occurrences of a string with another string in Python?
- Using the replace() method
- Example 1
- Output
- Example 2
- Output
- Using the regular expressions
- Example
- Output
- Traversing through each character
- Example
- Output
- Python regex replace: How to Search and Replace Strings
- Syntax
- Parameters
- Return value
- Example 1: How to search and replace string in Python
- Example 2: Specifying the count
- Replacing multiple patterns using regex
- Replacing multiple substrings with the exact string
- Replacing a string using the matched part
- Replacing a string by position using a slice
How to replace all occurrences of a string with another string in Python?
A string is a group of characters that may be used to represent a single word or an entire phrase. In Python strings not require explicit declaration and may be defined with or without a specifier therefore, it is easy to use them.
Python has various built in functions and methods for manipulating and accessing strings. Because everything in Python is an object, a string is an object of the String class, which has several methods.
In this article, we are going to focus on replacing all occurrences of a string with another string in python.
Using the replace() method
The replace() method of string class accepts a string value as input and returns the modified string as output. It has 2 mandatory parameters and 1 optional parameter. Following is the syntax of this method.
string.replace(oldvalue, newvalue, count)
- Old value − The substring that you want to replace.
- New value − This represents the substring with which you want to replace.
- Count − This is an optional parameter; it is used to specify the number of old values you want to replace with new values.
Example 1
In the program given below, we are taking an input string and by using the replace method we are replacing the letter “t” with “d”.
str1 = "Welcome to tutorialspoint" print("The given string is") print(str1) print("After replacing t with d") print(str1.replace("t","d"))
Output
The output of the above program is,
The given string is Welcome to tutorialspoint After replacing t with d Welcome do dudorialspoind
Example 2
In the program given below, we are taking the same input string and we are replacing the letter “t” with “d” using the replace() method, but in this example we are taking the count parameter as 2. So only 2 appearances of t are converted.
str1 = "Welcome to tutorialspoint" print("The given string is") print(str1) print("After replacing t with d for 2 times") print(str1.replace("t","d",2))
Output
The output of the above program is,
The given string is Welcome to tutorialspoint After replacing t with d for 2 times Welcome do dutorialspoint
Using the regular expressions
We can also use Python regular expressions to replace all occurrences of a string with another string. The sub() method of python re replaces an existing letter in the given string with a new letter. Following is the syntax of this method −
- Old − The sub string that you want to replace.
- New − The new sub string with which you want to replace.
- String − The source string.
Example
In the example given below, we are using the sub method of re library for replacing the letter “t” with “d”.
import re str1 = "Welcome to tutorialspoint" print("The given string is") print(str1) print("After replacing t with d ") print(re.sub("t","d",str1))
Output
The output of the above given program is,
The given string is Welcome to tutorialspoint After replacing t with d Welcome do dudorialspoind
Traversing through each character
Another approach is the brute force approach where you traverse each character of a particular string and check it with the character you want to replace, if it matches then replace that character else move forward.
Example
In the example given below, we are iterating over the string and matching each character and replacing them.
str1= "Welcome to tutorialspoint" new_str = '' for i in str1: if(i == 't'): new_str += 'd' else: new_str += i print("The original string is") print(str1) print("The string after replacing t with d ") print(new_str)
Output
The output of the above program is,
The original string is Welcome to tutorialspoint The string after replacing t with d Welcome do dudorialspoind
Python regex replace: How to Search and Replace Strings
To replace a string that matches the regex in Python, you can use the “re.sub()” method. The “re.sub()” method accepts the maximum five arguments and returns replaced strings.
Syntax
re.sub(pattern, repl, string, count=0, flags=0)
Parameters
- pattern: The regular expression pattern to find inside the target string.
- repl: The replacement that we are going to insert for each occurrence of a pattern. The replacement can be a string or function.
- string: The variable pointing to the target string (In which we want to perform the replacement).
- count: Maximum number of pattern occurrences to be replaced. The count must always be a positive integer if specified. By default, the count is set to zero, which means the re.sub() method will replace all pattern occurrences in the target string.
- flags: Finally, the last argument is optional and refers to regex flags. By default, no flags are applied.
Return value
It returns the string obtained by replacing the pattern occurrences in the string with the replacement string.
Example 1: How to search and replace string in Python
The re.sub() function in the “re” module can replace substrings.
To use the sub() method, first, we have to import the “re” module, and then we can use its sub() method.
import re str = 'aaa@gmail.com' print(re.sub('[a-z]*@', 'ApD@', str))
In the above example, we try to replace small letter cases from a to z before @ character.
From the output, we can see that we have successfully updated the email addresses.
If we use the string replace() method to replace the string, a new string will be replaced to match the old string entirely.
Example 2: Specifying the count
You can pass a count parameter in the regex sub() method. It suggests to the compiler that please don’t replace more than the count’s value.
import re str = 'aaa@gmail.com' print(re.sub('[a-z]*@', 'ApD@', str, 2))
ApD@gmail.com ApD@hotmail.com ccc@apple.com
The output shows that it replaced only two email addresses; the last address is as it is.
Replacing multiple patterns using regex
Use the regex to replace multiple patterns simultaneously using re.sub(pattern_1 | pattern_2, replacement, string, count= 0 , flags= 0 ) syntax.
import re str = "biden-Putin Volodymir Modi Abe Jacinda" print(re.sub("(\s) | (-)", ", ", str))
Replacing multiple substrings with the exact string
You can replace multiple substrings with the exact string by enclosing the string with [ ] to match any character.
str = 'aaa@gmail.com bbb@hotmail.com ccc@apple.com' print(re.sub('[a-z]*@', 'info@', str))
info@gmail.com info@hotmail.com info@apple.com
You can see that it replaces the same string with multiple substrings.
If | delimits patterns, it matches any pattern. And also, it is possible to use special characters of regular expression for each pattern, but it is OK even if the usual string is specified.
It can be used to replace multiple different strings with the same string.
import re str = 'aaa@gmail.com bbb@hotmail.com ccc@apple.com' print(re.sub('gmail|hotmail|apple', 'appdividend', str))
aaa@appdividend.com bbb@appdividend.com ccc@appdividend.com
You can see that all substring is replaced with appdividend.
Let’s see a scenario in which only one pattern matches.
import re str = 'aaa@gmail.com bbb@amazon.com ccc@walmart.com' print(re.sub('gmail|hotmail|apple', 'appdividend', str))
aaa@appdividend.com bbb@amazon.com ccc@walmart.com
You can see that bbb@amazon.com and ccc@walmart.com are unchanged.
Only aaa@gmail.com is replaced with aaa@appdividend.com.
Replacing a string using the matched part
To replace a substring using the matched part, use the string that matches the part enclosed in () in the new string.
import re str = 'aaa@gmail.com bbb@amazon.com ccc@walmart.com' print(re.sub('([a-z]*)@', '\1 19-@', str))
19-@gmail.com 19-@amazon.com 19-@walmart.com
The \1 corresponds to the part that matches (). If there are multiple ( ), use them like \2, \3 …
It is important to escape \ like \\1 if it is a regular string surrounded by the ” or ” “, but if it is the raw string with r at the beginning like r”, you can write \1.
Replacing a string by position using a slice
There is no method for specifying and replacing the position; dividing the slice and concatenating them with the arbitrary string can create a new string in which a specified position is replaced.
import re str = 'albertodelrio' print(str[:4] + 'HANAYA' + str[7:])
In the above code example, you can see that we have added a substring between string indexes 4 to 7.