使用Translate函数
Python3中的translate函数与Python2中已经不同了,使用Python3的方法如下.
maketrans(table,[deletion],[toNone])
函数是在处理字符串str的时候,将其中的table
中指定的字符一一对应映射成deletion
中指定的字符,将toNone
中指定的字符映射成None(即None).
例如:1
2
3
4
5import string
# string.punctuation中包含了常用的英文标点符号
translator = str.maketrans(dict.fromkeys(string.punctuation))
s = 'string with "punctuation" inside of it! Does this work? I hope so.'
print(s.translate(translator))