Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Python by (1.6k points)

It seems like there should be a simpler way than:

import string

s = "string. With. Punctuation?" # Sample string 

out = s.translate(string.maketrans("",""), string.punctuation)

Is there?

2 Answers

0 votes
by (25.1k points)

You can use the string.translate method as it is very fast and easy to use.

s.translate(None, string.punctuation)

For higher versions of Python use the following code:

s.translate(str.maketrans('', '', string.punctuation))

0 votes
by (106k points)
edited by

The best way to remove punctuation from a string in Python would be using regular expressions see the code below:-

import re s = "string. With. Punctuation?" 

s = re.sub(r'[^\w\s]','',s)

In the above code we are substituting(re.sub) all NON[alphanumeric characters(\w) and spaces(\s)] with an empty string.

So, the ‘ .’ and ‘?’ punctuation won't be present in variable 's' after runnings variable through the regex.

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
1 answer
asked Sep 20, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...