Remove punctuation. With the "in" operator and the string.punctuation constant, we can remove all punctuation chars from a string.
Note We add each character to our result that is not punctuation. Spaces (which are not punctuation) are kept.
result = ""
for c in value:
# If char is not punctuation, add it to the result.
if c not in string.punctuation:
result += c
# Test our method.
temp = "hello, friend!... welcome."
print(remove_punctuation(temp))hello, friend!... welcome.
hello friend welcome
Whitespace. Let us look at another occasionally-helpful constant in the string module: string.whitespace. This too can be looped over or tested.
Tip Instead of testing constant strings with "in," consider using methods like isspace().
print(" " in string.whitespace)
print("\n" in string.whitespace)
print("X" in string.whitespace)True
For performance, the in-operator is fast. But it will not outperform a specialized lookup table. We could use a dictionary to store a value indicating whether a char is punctuation or not.