Split on either a space or a hyphen?

后端 未结 3 432
半阙折子戏
半阙折子戏 2021-01-02 06:46

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

Input:

You think we did this un-thinkingly?
         


        
3条回答
  •  一生所求
    2021-01-02 06:54

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

提交回复
热议问题