0 votes
1 view
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 (21.4k 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 (95.7k 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
0 votes
1 answer
asked Sep 20 in Python by Sammy (41.8k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...