How to replace all occurrences of a character in a Python string
Overview
In Python, we can replace all occurrences of a character in a string using the following methods:
replace()re.sub()
The replace() method
replace() is a built-in method in Python that replaces all the occurrences of the old character with the new character.
Syntax
"".replace(oldCharacter, newCharacter, count)
Parameters
This method accepts the following parameters:
oldCharacter: This is the old character that will be replaced.newCharacter: This is the new character that will replace the old character.count: This is an optional parameter that specifies the number of times to replace the old character with the new character.
Return value
This method creates a copy of the original string, replaces all the occurrences of the old character with the new character, and returns it.
Example
string = "This is an example string"# replace all the occurrences of "i" with "I"result = string.replace("i", "I")# print resultprint(result)
Explanation
- Line 1: We declare a string.
- Line 4: We use the
replace()method to replace all the occurrences ofiwithI. - Line 7: We print the result to the console.
Output
In the output, we can see all the occurrences of i in the string are replaced with I.
The re.sub() method
We can also use regular expressions to replace all the occurrences of a character in a string. This can be done using re.sub() method.
Syntax
re.sub(oldCharacter, newCharacter, string)
Parameters
This method accepts the following parameters:
oldCharacter: This is the old character that will be replaced.newCharacter: This is the new character that will replace the old character.string: This is the string in which the characters are to be replaced.
Return value
This method creates a copy of the original string, replaces all the occurrences of the old character with the new character, and returns it.
Example
import restring = "This is an example string"# replace all the occurrences of "i" with "I"result = re.sub("i", "I", string)# print resultprint(result)
Explanation
- Line 1: We import the
remodule. - Line 3: We declare a string.
- Line 6: We use the
re.sub()method to replace all the occurrences ofiwithI. - Line 9: We print the result to the console.
Output
In the output, we can see all the occurrences of i in the string are replaced with I.