I'm trying to remove punctuations in a string called fs
using string.punctuation with the code:
fs = fs.translate({ord(i): None for i in string.punctuation})
In the text though, there are several underlines (_
)
How do I implement my code such that it ignores underlines and removes all others?
Is it like:
fs = fs.translate({ord(i): None for i in string.punctuation if '_' not in string.punctuation})
string.punctuation
is itself just a string, so we could just work with a modified version of the string: {ord(i): None for i in string.punctuation.replace('_', '')}
.
The more general technique you are looking for is: the if
will be checked separately for
each i
value, and suppress output (of a key-value pair for the dict) when the check is false. So the condition should not be like ... if '_' not in string.punctuation
, but instead simply ... if i != '_'
.