我有一個像刪除標點符號從Python的列表項
['hello', '...', 'h3.a', 'ds4,']
名單本應變成
['hello', 'h3a', 'ds4']
,我想只刪除標點留下字母和數字不變。 標點符號是string.punctuation
中的任何常數。 我知道,這是貢納是簡單的,但即時通訊有點noobie在蟒蛇所以...
感謝, giodamelio
我有一個像刪除標點符號從Python的列表項
['hello', '...', 'h3.a', 'ds4,']
名單本應變成
['hello', 'h3a', 'ds4']
,我想只刪除標點留下字母和數字不變。 標點符號是string.punctuation
中的任何常數。 我知道,這是貢納是簡單的,但即時通訊有點noobie在蟒蛇所以...
感謝, giodamelio
假設您的初始列表存儲在一個變量x,您可以使用此:
>>> x = [''.join(c for c in s if c not in string.punctuation) for s in x]
>>> print(x)
['hello', '', 'h3a', 'ds4']
刪除空字符串:
>>> x = [s for s in x if s]
>>> print(x)
['hello', 'h3a', 'ds4']
爲了使新的列表:
[re.sub(r'[^A-Za-z0-9]+', '', x) for x in list_of_strings]
這不會對列表做任何事情。 – nmichaels 2010-12-06 21:49:32
import string
print ''.join((x for x in st if x not in string.punctuation))
PS ST是字符串。對於清單是一樣的...
[''.join(x for x in par if x not in string.punctuation) for par in alist]
我覺得效果很好。看string.punctuaction:
>>> print string.punctuation
!"#$%&\'()*+,-./:;<=>[email protected][\\]^_`{|}~
使用string.translate:
>>> import string
>>> test_case = ['hello', '...', 'h3.a', 'ds4,']
>>> [s.translate(None, string.punctuation) for s in test_case]
['hello', '', 'h3a', 'ds4']
對於翻譯的文檔,請參閱http://docs.python.org/library/string.html
他不希望在的地方去掉標點符號... – 2010-12-06 21:52:02
很酷的工作很棒:) – giodamelio 2010-12-06 22:00:12