2

I have looked at several answers on Best way to strip punctuation from a string in Python but none of these seem to address my problem. I am trying to strip punctuation from a string using string.translate().

When I run the code:

import string
s = "This. has? punctuation," 
noPunct = s.translate(s.maketrans("",""), string.punctuation)

I get:

TypeError: translate() takes exactly one argument (2 given)

Is this perhaps an issue with the python version I am using? I am using python 3.5.4 for compatibility with nltk. Otherwise I am stumped. Any help would be appreciated.

Francis
  • 23
  • 4

3 Answers3

1

You're using Python 2.x code, but running Python 3.x. Scroll down on the linked question to see how to do it in Python 3.x:

s.translate(mapping)
Ignacio Vazquez-Abrams
  • 699,552
  • 132
  • 1,235
  • 1,283
1

The Python 3 interface for str.translate uses a mapping. Make one with str.maketrans:

>>> import string
>>> table = str.maketrans({}.fromkeys(string.punctuation))
>>> "This. has? punctuation,".translate(table)
'This has punctuation'
wim
  • 266,989
  • 79
  • 484
  • 630