Replacing characters in strings using Python can be done with multiple ways. In this quick tutorial, you’ll learn how to use the
replace method to manipulate strings.
You’ll learn through examples how to replace a character in a string, how to replace multiple characters in a string, and how to replace the last character in a string.
replace(old, new, count) method takes three inputs:
old: the string you want to replace
new: the string you want to replace with
count: (optional) how many occurrences you want this replacement to occur
How to replace a character in a string in Python
Let’s start with replacing one character in string:
s1 = 'Salam!' s1 = s1.replace('!', '.') print(s1) # Salam.
Here, we’ve replace the exclamation mark with a dot. We start with defining the
s1 string. Because everything in Python is an object, a string is obviously an object. That
replace method is applied on that
string object with the first argument as the exclamation mark (the character we want to replace). While the second argument is the dot (the character we want to replace with).
The new character that you want to replace the old could have multiple characters:
s1 = 'Salam!' s1 = s1.replace('!', '...') print(s1) # Salam...
So the exclamation mark is now replaced with three dots.
With this knowledge, you can remove a character in a string by replacing it with nothing:
s1 = 'Salam!' s1 = s1.replace('!', '') print(s1) # Salam
So nothing here is an empty string. So that exclamation mark is removed from the old string.
Replace multiple characters in string
You can also replace the old string multiple times:
s2 = '436313' s2 = s2.replace('3', '2') print(s2) # 426212
Or you can specify how many number of occurrences of that
3 string that you want to replace:
s3 = '436313' s3 = s3.replace('3', '2', 2) print(s3) # 426213
Replace last character in string
If you want to replace the last character in a string, you can reverse the string first:
s3 = '436313' s3_reverse = s3[::-1]
And then replace the old character with the first occurrence in the reversed string:
s4 = s3_reverse.replace('3', '2', 1)
and then reverse back that new string result: