python - 如何使用 Python 将字符串拆分为多个标点符号?
问题描述
s = 'a,b,c d!e.f\ngood\tmorning&night'
delimiters = [',', '.', '!', '&', '', '\n', '\t']
s.split()
我可以将字符串全部拆分',', '.', '!', '&', ' ', '\n', '\t'
吗?是否可以为 指定多个分隔符string.split()
?例如,我怎样才能s
分成
['a','b','c','d','e','f','good','morning','night']
解决方案
您可以使用regex
以下方式实现此目的:
>>> import re
>>> s = 'a,b,c d!e.f\ngood\tmorning&night'
>>> re.split('[?.,\n\t&! ]', s)
['a', 'b', 'c', 'd', 'e', 'f', 'good', 'morning', 'night']
如果您正在寻找使用 的解决方案split()
,那么这里有一个解决方法:
>>> identifiers = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~\n\t '
>>> "".join((' ' if c in identifiers else c for c in s)).split()
['a', 'b', 'c', 'd', 'e', 'f', 'good', 'morning', 'night']
在这里,我将" "
字符串中的所有标识符替换为空格,然后根据空格拆分字符串。