Python: space division or hyphen?

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

Entrance:

You think we did this un-thinkingly? 

Required Conclusion:

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

I can walk to

 mystr.split(' ') 

But I don't know how to split into hyphens, as well as spaces and the Python definition for splitting only seems to indicate a string . Do I need to use regex?

+6
source share
3 answers

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

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

Otherwise, use RE as suggested by @jamylak .

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

As noted by @larsmans, to break into multiple spaces / hyphens (emulating .split() with no arguments), it is used [...] to read:

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

Without regex (in this case, regex is the easiest option):

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

Actually @Elazar's answer without regex is also quite simple (I vouch for regex anyway)

+14
source

A regular expression is much simpler and better, but if you are strongly against it:

 import itertools itertools.chain.from_iterable((i.split(" ") for i in myStr.split("-"))) 
+1
source

Source: https://habr.com/ru/post/946533/


All Articles