To replace a character in a string with another character in Python, you can use the replace()
method. Here is an example:
main.py81 chars4 lines
Output:
main.py14 chars2 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.py113 chars6 lines
Output:
main.py14 chars2 lines
Alternatively, you can use the translate()
method along with the maketrans()
function to perform character replacements. Here is an example:
main.py136 chars5 lines
Output:
main.py14 chars2 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.
gistlibby LogSnag