How to replace a character in a string in Python
![](https://pythonpoint.net/wp-content/uploads/2020/11/How-to-replace-a-character-in-a-string-in-Python-1024x576.jpg)
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