我有多个字符串,其中单词用逗号或句点分隔:
string = ['apple,pear,grapes,carrot.cabbage,veggies.fruit,yard']
我想根据逗号和句点分割它:
string = ['apple','pear','grapes','carrot','cabbage','veggies','fruit','yard']
我只知道如何使用一个条件进行 re.split:
re.split(',',string)
这不会分割中间有句点的单词。如何拆分整个字符串,以便在中间有逗号或句点时拆分单词?
最佳答案
>>> import re
>>> string = 'apple,pear,grapes,carrot.cabbage,veggies.fruit,yard'
>>> re.split(',|\.',string)
['apple', 'pear', 'grapes', 'carrot', 'cabbage', 'veggies', 'fruit', 'yard']
这会拆分为 ,
或.
(必须转义为 \.
)使用更改运算符 |
.
也可以用字符类来写:
>>> re.split('[,.]',string)
['apple', 'pear', 'grapes', 'carrot', 'cabbage', 'veggies', 'fruit', 'yard']
但这不太通用,因为这两个字符都不能用短语替换。
关于python - 如何对逗号和句号使用 re.split?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44099714/