我有一个字符串,我想用它去掉所有标点符号。我目前使用:
import string
translator = str.maketrans('','', string.punctuation)
name = name.translate(translator)但是,对于作为名称的字符串,这也删除了连字符,我希望将其保留在字符串中。例如,‘\Fred-Daniels!’应该变成‘Fred-Daniels’。
我如何修改上面的代码来实现这一点呢?
发布于 2017-08-01 09:13:28
如果你想从string.puncation中排除一些标点符号,你可以简单地删除那些你不想考虑的:
>>> from string import punctuation
>>> from re import sub
>>>
>>> string = "\Fred-Daniels!"
>>> translator = str.maketrans('','', sub('\-', '', punctuation))
>>> string
'\\Fred-Daniels!'
>>> string = string.translate(translator)
>>> string
'Fred-Daniels'注如果您只想排除一两个字符,则应该使用str.replace。否则,最好还是坚持使用re.sub。
发布于 2020-05-20 11:02:25
import string
PUNCT_TO_REMOVE = string.punctuation
print(PUNCT_TO_REMOVE) # Output : !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
# Now suppose you don't want _ in your PUNCT_TO_REMOVE
PUNCT_TO_REMOVE = PUNCT_TO_REMOVE.replace("_","")
print(PUNCT_TO_REMOVE) # Output : !"#$%&'()*+,-./:;<=>?@[\]^`{|}~发布于 2017-08-01 10:01:58
根据用例的不同,显式列出有效字符可能更安全、更清晰:
>>> name = '\\test-1.'
>>> valid_characters = 'abcdefghijklmnopqrstuvwxyz1234567890- '
>>> filtered_name = ''.join([ x for x in name if x.lower() in valid_characters ])
>>> print(filtered_name)
test-1请注意,许多人的名字都包含标点符号,如"Mary St.Cloud-Stevens“、"Jim Chauncey,Jr.”等。
https://stackoverflow.com/questions/45427439
复制相似问题