How to replace characters in a string in Python?
Published on Aug. 22, 2023, 12:17 p.m.
To replace characters in a string in Python, you can use the replace()
method. The replace()
method returns a new string where all occurrences of a specified character or substring are replaced with another character or substring.
Here’s an example:
my_string = "Hello, world!"
new_string = my_string.replace(",", ";")
print(new_string)
Output:
"Hello; world!"
In this example, we have defined a string with a comma character. We then call the replace()
method on the string to replace the comma character with a semicolon character, and store the result in a new string.
Note that replace()
creates a new string, and does not modify the original string. If you want to modify the original string, you can re-assign the result of the replace()
method back to the original variable.
You can also replace multiple occurrences of a string or character by chaining the replace()
method. For example:
my_string = "Hello, world!"
new_string = my_string.replace(",", "").replace(" ", "")
print(new_string)
Output:
"Helloworld!"
In this example, we have removed both the comma and the space characters from the string by chaining two replace()
methods.