How to remove specific characters from a string in Python
Published on Aug. 22, 2023, 12:16 p.m.
To remove specific characters from a string in Python, you can use the str.replace()
method or the str.translate()
method. Here are some examples:
Using str.replace()
:
s = "Hello, world!"
s = s.replace(",", "") # remove commas
print(s) # "Hello world!"
Using str.translate()
:
s = "Hello, world!"
s = s.translate(str.maketrans("", "", ",")) # remove commas using translate
print(s) # "Hello world!"
Both of these methods create a new string object rather than modifying the original string in place, since strings are immutable in Python.