0

I have the following string

t1 = 'hello, how are you ?'

I just want to get this :

t2 = 'hello how are you'

So I'm trying to use sub() from with a negate regex like this :

t2 = re.sub(r'^([a-z])','',t1)

But I don't succeed in.

What is the best way to remove punctuations ?

Thanks

Junayy
  • 1,130
  • 7
  • 13
  • 1
    I hope this will help http://stackoverflow.com/questions/265960/best-way-to-strip-punctuation-from-a-string-in-python – f43d65 Jun 11 '15 at 21:08

3 Answers3

1

Try something like this:

re.sub("[^a-zA-Z ]","",'hello, how are you ?').rstrip()

The rstrip is there to get rid of the trailing whitespace left after getting rid of the question mark.

Of course, this is only if you really want to use regex. Any of the ways in the question that @f43d65 linked will probably work fine and likely be faster as well.

Blair
  • 6,623
  • 1
  • 36
  • 42
1

The best way to remove punctuation doesn't use regular expressions.

# Python 3
import string

transmapping = str.maketrans(None, None, string.punctuation)

t1 = 'hello, how are you ?'
t2 = t1.translate(transmapping).strip()

Here are the Python3 docs for str.maketrans and str.translate

# Python 2
import string

t1 = 'hello, how are you ?'
t2 = t1.translate(None, deletechars=string.punctuation).strip()

Here are the Python2 docs for string.maketrans (not used here) and str.translate

Using regular expressions to do string translation is a bit like using a backhoe when a prybar would do. It's huge, unwieldy, and likely to foul things up if you don't do it juuuust right.

Adam Smith
  • 52,157
  • 12
  • 73
  • 112
0

Assuming you only want to remove the last punctuation and it's a question mark:

/[\?]$/

That's saying remove anything in the brackets that's at the end of a string.

Chad
  • 200
  • 4