If you are looking for replacing instances of a character in a string, Python has a built-in
replace() method which does the task for you.
The replace method replaces each matching occurrence of the old characters/substring with the new characters/substring.
string.replace(old, new, count)
- old – character or substring you want to replace.
- new – a new character or substring which would replace the old substring.
- count (optional)– the number of times you want to replace the old substring with the new substring
This method returns a copy of the string, where the old substring is replaced with a new one, keeping the original string unchanged. If the old string is not found, the copy of the original string is returned.
Example 1 – Replace all the instances of a character in a given string
# replace all the characters in a string sample_text = 'All the, commas, will, be, replaced by empty string, in this,, sentence,' print(sample_text.replace(',', ''))
All the commas will be replaced by empty string in this sentence
Example 2 – Replace all the instances of a substring in a given string
# replace the old substring with new substring sample_text2 = 'This is a wrong sentence' print(sample_text2.replace('wrong', 'correct'))
This is a correct sentence
Example 3 – Replace only one instances of a substring in a given string
# replace substring of only one occurence sample_text3 = 'int, string, bool, byte, string, float, bit, string' print(sample_text3.replace('string', 'char',1))
int, char, bool, byte, string, float, bit, string
Example 4 – Replace character in string at index
# Replace character in string at index sample_text4 = 'Europx' new_text ='e' print(sample_text4[:5] + new_text + sample_text4[5+1:])