In Python, we can replace all occurrences of a character in a string using the following methods:
replace()
re.sub()
replace()
methodreplace()
is a built-in method in Python that replaces all the occurrences of the old character with the new character.
"".replace(oldCharacter, newCharacter, count)
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.This method creates a copy of the original string, replaces all the occurrences of the old character with the new character, and returns it.
string = "This is an example string"# replace all the occurrences of "i" with "I"result = string.replace("i", "I")# print resultprint(result)
replace()
method to replace all the occurrences of i
with I
.In the output, we can see all the occurrences of i
in the string are replaced with I
.
re.sub()
methodWe can also use regular expressions to replace all the occurrences of a character in a string. This can be done using re.sub()
method.
re.sub(oldCharacter, newCharacter, string)
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.This method creates a copy of the original string, replaces all the occurrences of the old character with the new character, and returns it.
import restring = "This is an example string"# replace all the occurrences of "i" with "I"result = re.sub("i", "I", string)# print resultprint(result)
re
module.re.sub()
method to replace all the occurrences of i
with I
.In the output, we can see all the occurrences of i
in the string are replaced with I
.