在Python中,如何拆分空格或连字符?
输入:
You think we did this un-thinkingly?
期望的输出:
["You", "think", "we", "did", "this", "un", "thinkingly"]
我可以达到
mystr.split(' ')
但我不知道如何拆分连字符和空格and the Python definition of split only seems to specify a string。我需要使用正则表达式吗?
答案 0 :(得分:19)
答案 1 :(得分:15)
>>> import re
>>> text = "You think we did this un-thinkingly?"
>>> re.split(r'\s|-', text)
['You', 'think', 'we', 'did', 'this', 'un', 'thinkingly?']
正如@larsmans所指出的那样,要用多个空格/连字符(没有参数模拟.split()
)进行拆分,使用[...]
来提高可读性:
>>> re.split(r'[\s-]+', text)
['You', 'think', 'we', 'did', 'this', 'un', 'thinkingly?']
没有正则表达式(正则表达式是这种情况下最直接的选项):
>>> [y for x in text.split() for y in x.split('-')]
['You', 'think', 'we', 'did', 'this', 'un', 'thinkingly?']
实际上@Elazar没有正则表达式的答案也很简单(虽然我仍然会保证正则表达式)
答案 2 :(得分:1)
正则表达式更容易,更好,但如果你坚决反对使用正则表达式:
import itertools
itertools.chain.from_iterable((i.split(" ") for i in myStr.split("-")))