Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all the punctuation in a string? (Python) [duplicate]

Tags:

python

For example:

asking="hello! what's your name?"

Can I just do this?

asking.strip("!'?")
like image 910
Wuchun Aaron Avatar asked Apr 17 '13 03:04

Wuchun Aaron


People also ask

How do I remove all punctuation from a string in Python?

One of the easiest ways to remove punctuation from a string in Python is to use the str. translate() method. The translate() method typically takes a translation table, which we'll do using the . maketrans() method.

How do I remove multiple special characters from a string in Python?

Removing symbol from string using replace() One can use str. replace() inside a loop to check for a bad_char and then replace it with the empty string hence removing it.

How do I remove all characters from a string in Python?

Python Remove Character from a String – How to Delete Characters from Strings. In Python you can use the replace() and translate() methods to specify which characters you want to remove from a string and return a new modified string result.


1 Answers

A really simple implementation is:

out = "".join(c for c in asking if c not in ('!','.',':'))

and keep adding any other types of punctuation.

A more efficient way would be

import string
stringIn = "string.with.punctuation!"
out = stringIn.translate(stringIn.maketrans("",""), string.punctuation)

Edit: There is some more discussion on efficiency and other implementations here: Best way to strip punctuation from a string in Python

like image 156
Øyvind Robertsen Avatar answered Oct 11 '22 13:10

Øyvind Robertsen