Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Regex Compile Split string so that words appear first

Say I was given a string like so

text = "1234 I just ? shut * the door"

I want to use a regex with re.compile() such that when I split the list all of the words are in front.

I.e. it should look like this.

text = ["I", "just", "shut", "the", "door", "1234", "?", "*"]

How can I use re.compile() to split the string this way?

import re
r = re.compile('regex to split string so that words are first').split(text)

Please let me know if you need any more information.

Thank you for the help.

like image 364
mrsquid Avatar asked Jan 27 '26 01:01

mrsquid


1 Answers

IIUC, you don't need re. Just use str.split with sorted:

sorted(text.split(), key=lambda x: not x.isalpha())

Output:

['I', 'just', 'shut', 'the', 'door', '1234', '?', '*']
like image 185
Chris Avatar answered Jan 29 '26 13:01

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!