【问题标题】:How to split at spaces and commas in Python?如何在 Python 中以空格和逗号分隔?
【发布时间】:2016-11-18 11:18:36
【问题描述】:

我一直在这里四处寻找,但没有找到任何与我的问题相关的东西。我正在使用 Python3。 我想在每个空格和逗号处分割一个字符串。这是我现在得到的,但我得到了一些奇怪的输出: (别担心,这句话是从德语翻译过来的)

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

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

我真正想要的是:

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

【问题讨论】:

  • 逗号在这里看起来很重要:),但你不需要转义它
  • 有关这些空字符串的更多信息,请参见 Why are empty strings returned in split() results?
  • 确实逗号很重要(德语),否则你会吃奶奶:),谢谢拉德雷克萨斯,我会看看

标签: python regex split


【解决方案1】:

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

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

【讨论】:

  • 是的,非常有效!尽管我不明白我的尝试有什么不同!谢谢!
  • 主要区别是使用findall而不是split
【解决方案2】:

另一种方式:

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

【讨论】:

  • 你的提案产生:['We', 'eat', '', 'Granny']
【解决方案3】:

这应该适合你:

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

【讨论】:

  • 它以某种方式产生:
猜你喜欢
  • 2018-03-22
  • 2011-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-23
  • 2018-11-07
相关资源
最近更新 更多