Split on either a space or a hyphen?

£可爱£侵袭症+ 提交于 2019-12-19 02:06:23

问题


In Python, how do I split on either a space or a hyphen?

Input:

You think we did this un-thinkingly?

Desired output:

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

I can get as far as

mystr.split(' ')

But I don't know how to split on hyphens as well as spaces and the Python definition of split only seems to specify a string. Do I need to use a regex?


回答1:


If your pattern is simple enough for one (or maybe two) replace, use it:

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

Otherwise, use RE as suggested by @jamylak.




回答2:


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

As @larsmans noted, to split by multiple spaces/hyphens (emulating .split() with no arguments) used [...] for readability:

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

Without regex (regex is the most straightforward option in this case):

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

Actually the answer by @Elazar without regex is quite straightforward as well (I would still vouch for regex though)




回答3:


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("-")))


来源:https://stackoverflow.com/questions/16926870/split-on-either-a-space-or-a-hyphen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!