在 Python 中,如何拆分空格或连字符?
输入:
You think we did this un-thinkingly?
期望的输出:
["You", "think", "we", "did", "this", "un", "thinkingly"]
我能走多远
mystr.split(' ')
但我不知道如何在连字符和空格上进行拆分,并且 Python 的 split 定义似乎只指定了一个 string。我需要使用正则表达式吗?
在 Python 中,如何拆分空格或连字符?
输入:
You think we did this un-thinkingly?
期望的输出:
["You", "think", "we", "did", "this", "un", "thinkingly"]
我能走多远
mystr.split(' ')
但我不知道如何在连字符和空格上进行拆分,并且 Python 的 split 定义似乎只指定了一个 string。我需要使用正则表达式吗?
>>> 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没有正则表达式的答案也很简单(尽管我仍然保证正则表达式)
A regex is far easier and better, but if you're staunchly opposed to using one:
import itertools
itertools.chain.from_iterable((i.split(" ") for i in myStr.split("-")))