For example:
asking="hello! what's your name?"
Can I just do this?
asking.strip("!'?")
One of the easiest ways to remove punctuation from a string in Python is to use the str. translate() method. The translate() method typically takes a translation table, which we'll do using the . maketrans() method.
Removing symbol from string using replace() One can use str. replace() inside a loop to check for a bad_char and then replace it with the empty string hence removing it.
Python Remove Character from a String – How to Delete Characters from Strings. In Python you can use the replace() and translate() methods to specify which characters you want to remove from a string and return a new modified string result.
A really simple implementation is:
out = "".join(c for c in asking if c not in ('!','.',':'))
and keep adding any other types of punctuation.
A more efficient way would be
import string
stringIn = "string.with.punctuation!"
out = stringIn.translate(stringIn.maketrans("",""), string.punctuation)
Edit: There is some more discussion on efficiency and other implementations here: Best way to strip punctuation from a string in Python
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With