如何拆分python中的空格和逗号?

时间:2016-11-18 11:18:37

标签: python regex split

我一直在这里寻找,但没有发现任何接近我的问题。我使用python3。 我想在每个空格和逗号分割一个字符串。这是我现在得到的,但我得到一些奇怪的输出: (不要担心从德语翻译的句子)

    import re
    sentence = "We eat, Granny" 
    split = re.split(r'(\s|\,)', sentence.strip())
    print (split)

    >>>['We', ' ', 'eat', ',', '', ' ', 'Granny']

我真正想要的是:

    >>>['We', ' ', 'eat', ',', ' ', 'Granny']

3 个答案:

答案 0 :(得分:1)

替代方式:

split = [a for a in re.split(r'(\s|\,)', sentence.strip()) if a]

答案 1 :(得分:1)

我会选择findall而不是分割,只需匹配所有需要的内容,例如

import re
sentence = "We eat, Granny" 
print(re.findall(r'\s|,|[^,\s]+', sentence))

答案 2 :(得分:0)

这应该适合你:

 import re
 sentence = "We eat, Granny" 
 split = list(filter(None, re.split(r'(\s|\,)', sentence.strip())))
 print (split)
相关问题