Sometimes, we want to strip punctuation from a string with Python.
In this article, we’ll look at how to strip punctuation from a string with Python.
How to strip punctuation from a string with Python?
To strip punctuation from a string with Python, we can use the string’s translate
method.
For instance, we can write:
import string
s = 'hello world!!!'
new_s = s.translate(str.maketrans('', '', string.punctuation))
print(new_s)
to call s.translate
with str.maketrans('', '', string.punctuation)
to return a new string without the punctuation characters in it.
Then we assign that to new_s
.
Therefore, new_s
is 'hello world'
.
Conclusion
To strip punctuation from a string with Python, we can use the string’s translate
method.