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?
As @larsmans noted, to split by multiple spaces/hyphens (emulating
.split()
with no arguments) used[...]
for readability:Without regex (regex is the most straightforward option in this case):
Actually the answer by @Elazar without regex is quite straightforward as well (I would still vouch for regex though)
A regex is far easier and better, but if you're staunchly opposed to using one:
If your pattern is simple enough for one (or maybe two)
replace
, use it:Otherwise, use RE as suggested by @jamylak.