Python:拆分空格还是连字符?

Ric*_*ard 7 python string formatting

在Python中,如何拆分空格或连字符?

输入:

You think we did this un-thinkingly?
Run Code Online (Sandbox Code Playgroud)

期望的输出:

["You", "think", "we", "did", "this", "un", "thinkingly"]
Run Code Online (Sandbox Code Playgroud)

我可以得到

mystr.split(' ')
Run Code Online (Sandbox Code Playgroud)

但我不知道如何拆分连字符和空格,并且拆分的Python定义似乎只指定了一个字符串.我需要使用正则表达式吗?

Ela*_*zar 22

如果您的模式对于一个(或两个)足够简单replace,请使用它:

mystr.replace('-', ' ').split(' ')
Run Code Online (Sandbox Code Playgroud)

否则,请按@jamylak的建议使用RE .


jam*_*lak 15

>>> import re
>>> text = "You think we did this un-thinkingly?"
>>> re.split(r'\s|-', text)
['You', 'think', 'we', 'did', 'this', 'un', 'thinkingly?']
Run Code Online (Sandbox Code Playgroud)

正如@larsmans所指出的那样,用多个空格/连字符(.split()没有参数模拟)进行拆分[...]用于可读性:

>>> re.split(r'[\s-]+', text)
['You', 'think', 'we', 'did', 'this', 'un', 'thinkingly?']
Run Code Online (Sandbox Code Playgroud)

没有正则表达式(在这种情况下正则表达式是最直接的选项):

>>> [y for x in text.split() for y in x.split('-')]
['You', 'think', 'we', 'did', 'this', 'un', 'thinkingly?']
Run Code Online (Sandbox Code Playgroud)

实际上@Elazar没有正则表达式的答案也很简单(我仍然会保证正则表达式)