replace a char in string with another in python

To replace a character in a string with another character in Python, you can use the replace() method. Here is an example:

main.py
string = "Hello, World!"
new_string = string.replace("o", "x")
print(new_string)
81 chars
4 lines

Output:

main.py
Hellx, Wxrld!
14 chars
2 lines

In the above example, we are replacing all occurrences of the character 'o' with the character 'x' in the string. The replace() method returns a new string with the replacements made.

Note that the replace() method is case-sensitive. If you want to perform a case-insensitive replacement, you can use the re module or convert the string to lowercase or uppercase before performing the replacement.

main.py
import re

string = "Hello, World!"
new_string = re.sub("o", "x", string, flags=re.IGNORECASE)
print(new_string)
113 chars
6 lines

Output:

main.py
Hellx, Wxrld!
14 chars
2 lines

Alternatively, you can use the translate() method along with the maketrans() function to perform character replacements. Here is an example:

main.py
string = "Hello, World!"
translation_table = str.maketrans("o", "x")
new_string = string.translate(translation_table)
print(new_string)
136 chars
5 lines

Output:

main.py
Hellx, Wxrld!
14 chars
2 lines

In this case, the maketrans() function creates a translation table where each occurrence of the character 'o' is mapped to the character 'x'. The translate() method then applies the translation table to the string to perform the replacements.

related categories

gistlibby LogSnag