How to replace a character in a string in Python

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.
Syntax:
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.
Example:
str = "I love chocolates" print ( str) print ( str.replace("chocolates","apples"))
Output:
I love chocolates I love apples
Subscribe
Login
Please login to comment
0 Discussion