您可以刪除標點與str.translate:
s = 'Hi, you!'
from string import punctuation
print(s.translate(None,punctuation).lower())
hi you
對於python3:
s = 'Hi, you!'
from string import punctuation
print(s.translate({ord(k):"" for k in punctuation}).lower())
hi you
在功能:
from string import punctuation
def remove_punctuation(s):
return s.translate(None,punctuation).lower()
def remove_punctuation(s):
return s.translate({ord(k): "" for k in punctuation}).lower()
輸出:
In [3]: remove_punctuation(' No under_score!')
Out[3]: ' no underscore'
In [4]: remove_punctuation('Hi, you!')
Out[4]: 'hi you'
如果你想刪除前導空格添加帶。
from string import punctuation
def remove_punctuation(s):
return s.translate(None,punctuation).lower().strip()
輸出:
In [6]: remove_punctuation(' No under_score!')
Out[6]: 'no underscore'
In [7]: remove_punctuation('Hi, you!')
Out[7]: 'hi you'
您是否也想刪除開頭和結尾的空格? – pzp