Remove Punctuations from a Python string
This post will discuss how to remove punctuations from a string in Python.
The solution should remove all English punctuations from the string like a full stop, comma, double-quotes, apostrophe, a hyphen, question mark, colon, exclamation mark, and semicolon.
1. Using str.translate() function
An efficient solution is to use the str.translate() function to remove all punctuations from a string. It simply maps each character of the string through a translation table, which can be easily created with the str.maketrans() function.
|
1 2 3 4 5 6 7 8 9 |
import string if __name__ == '__main__': s = 'Hello, World.' s = s.translate(str.maketrans('', '', string.punctuation)) print(s) # Hello World |
You can also specify a dictionary to str.maketrans() function.
|
1 2 3 4 5 6 7 8 9 |
import string if __name__ == '__main__': s = 'Hello, World.' s = s.translate(str.maketrans({key: None for key in string.punctuation})) print(s) # Hello World |
Here’s another solution that directly creates character mappings using a dictionary:
|
1 2 3 4 5 6 7 8 9 |
import string if __name__ == '__main__': s = 'Hello, World.' s = s.translate(dict.fromkeys(map(ord, string.punctuation))) print(s) # Hello World |
2. Using Regex
Another option is to use Regular expressions for finding and removing punctuations from a string. Here’s what the regex-based solution would look like:
|
1 2 3 4 5 6 7 8 9 |
import re if __name__ == '__main__': s = 'Hello, World.' s = re.sub(r'[.,"\'-?:!;]', '', s) print(s) # Hello World |
If you have a punctuation string, you can use the following code. It uses the re.escape() function to escape special characters.
|
1 2 3 4 5 6 7 8 9 10 |
import re, string if __name__ == '__main__': s = 'Hello, World.' chars = '[%s]+' % re.escape(string.punctuation) s = re.sub(chars, '', s) print(s) # Hello World |
3. Using Generator Expression
Finally, you can write a simple generator expression that filters punctuation marks from a string. The following example demonstrates.
|
1 2 3 4 5 6 7 8 9 |
import string if __name__ == '__main__': s = 'Hello, World.' s = ''.join(c for c in s if c not in string.punctuation) print(s) # Hello World |
Here’s a solution using lambda:
|
1 2 3 4 5 6 7 8 9 |
import string if __name__ == '__main__': s = 'Hello, World.' s = ''.join(filter(lambda x: x not in string.punctuation, s)) print(s) # Hello World |
That’s all about removing Punctuations from a string in Python.
Also See:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)