#import the regex library (pip install it with -> "pip install regex" import re test_phrase = 'This is a string! Bust it has punctuation. How can we remove it?' #We're going to replace the punctution with a whitespace clean = ' '.join(re.findall('[^!.?]+', test_phrase)) # ^ Place the punctuation that you want # to remove in the square brackets. print(clean) > 'This is a string But it has punctuation How can we remove it'
Here is what the above code is Doing:
1. We’re using the re.findall() method to find all non-punctuation characters.
2. We’re joining them together with a space character.
3. We’re printing the result.
You can also use the re.sub() method to replace punctuation with whitespace.