To replace a single character in a Python string, you can use the replace()
method as shown below:
main.py85 chars4 lines
The above code will output:
main.py12 chars2 lines
Here, the replace()
method takes two arguments: the old character to be replaced, and the new character to replace it with.
Note that this method only replaces the first occurrence of the old character. To replace all occurrences, you can use a combination of replace()
and join()
methods like so:
main.py108 chars4 lines
The above code will output:
main.py12 chars2 lines
Here, we are using a list comprehension to iterate over each character in the string, replacing 'o' with 'X' where needed. Then we join the resulting list back into a string.
gistlibby LogSnag