To replace a character in a string in Python, we can use the method replace(). This will return a copy of the string with replacements made.
str.replace(old, new[, max])
- old − the character/substring to be replaced.
- new − new character/substring, which would replace old character/substring.
- max − optional argument. if this is given, only the first count occurrences are replaced.
str = "I love chocolates" print ( str) print ( str.replace("chocolates","apples"))
I love chocolates I love apples