13

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

输入:

You think we did this un-thinkingly?

期望的输出:

["You", "think", "we", "did", "this", "un", "thinkingly"]

我能走多远

mystr.split(' ')

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

4

3 回答 3

29

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

mystr.replace('-', ' ').split(' ')

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

于 2013-06-04T20:33:17.107 回答
16
>>> 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没有正则表达式的答案也很简单(尽管我仍然保证正则表达式)

于 2013-06-04T20:29:06.427 回答
1

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("-")))
于 2013-06-04T20:32:16.393 回答