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?
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.
Use the str. split() method to split a string by hyphen, e.g. my_list = my_str. split('-') .
Use the str. split() method to split a string on the colons, e.g. my_list = my_str. split(':') .
>>> 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)
If your pattern is simple enough for one (or maybe two) replace
, use it:
mystr.replace('-', ' ').split(' ')
Otherwise, use RE as suggested by @jamylak.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With