replace a character in a string in python

To replace a single character in a Python string, you can use the replace() method as shown below:

main.py
my_string = "hello world"
new_string = my_string.replace('o', 'X')
print(new_string)
85 chars
4 lines

The above code will output:

main.py
hellX wXrld
12 chars
2 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.py
my_string = "hello world"
new_string = ''.join('X' if c == 'o' else c for c in my_string)
print(new_string)
108 chars
4 lines

The above code will output:

main.py
hellX wXrld
12 chars
2 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