[英]Openpyxl with Python - How to delete spaces and replace with commas
[英]How to split at spaces and commas in Python?
我一直在这里环顾四周,但没有发现任何与我的问题接近的问题。 我正在使用 Python3。 我想在每个空格和逗号处拆分一个字符串。 这是我现在得到的,但我得到了一些奇怪的输出:(别担心,这句话是从德语翻译过来的)
import re
sentence = "We eat, Granny"
split = re.split(r'(\s|\,)', sentence.strip())
print (split)
>>>['We', ' ', 'eat', ',', '', ' ', 'Granny']
我真正想要的是:
>>>['We', ' ', 'eat', ',', ' ', 'Granny']
我会去 findall 而不是 split 只匹配所有想要的内容,比如
import re
sentence = "We eat, Granny"
print(re.findall(r'\s|,|[^,\s]+', sentence))
替代方式:
split = [a for a in re.split(r'(\s|\,)', sentence.strip()) if a]
这应该适合你:
import re
sentence = "We eat, Granny"
split = list(filter(None, re.split(r'(\s|\,)', sentence.strip())))
print (split)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.