Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split on either a space or a hyphen?

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?

like image 848
Richard Avatar asked Jun 04 '13 20:06

Richard


People also ask

How do you split a string with a hyphen?

Use the split() method to split a string by hyphen, e.g. str. split('-') . The split method takes a separator as a parameter and splits the string by the provided separator, returning an array of substrings.

How do you split a string by a hyphen in Python?

Use the str. split() method to split a string by hyphen, e.g. my_list = my_str. split('-') .

How do you split text into colon in Python?

Use the str. split() method to split a string on the colons, e.g. my_list = my_str. split(':') .


2 Answers

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

like image 195
jamylak Avatar answered Oct 16 '22 17:10

jamylak


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

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

Otherwise, use RE as suggested by @jamylak.

like image 40
Elazar Avatar answered Oct 16 '22 16:10

Elazar