Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using 'or' condition in re.split

Tags:

python

split

I have a list of strings each one of those needs to be split when an 'y' or 'm' is found:

mylist = ['3m10y','10y20y','18m2y']

in the following items:

splitlist = [['3m','10y'],['10y','20y'],['18m','2y']]

i was thinking of using re.split() but I cannot use the 'or' condition in order to tell the function to split either when it finds an 'm' or an 'y'.

any help appreciated! thanks

like image 960
mspadaccino Avatar asked Jun 25 '26 09:06

mspadaccino


2 Answers

Try findall instead of split:

>>> re.findall(r'\d+[ym]', '3m10y')
['3m', '10y']

[my] is m or y.

like image 130
Fred Foo Avatar answered Jun 30 '26 19:06

Fred Foo


>>> items = re.split(r'(m|y)', '10m2y4m55y55y53m')
>>> items
['10', 'm', '2', 'y', '4', 'm', '55', 'y', '55', 'y', '53', 'm', '']
>>> [''.join(p) for p in zip(items[::2], items[1::2])]
['10m', '2y', '4m', '55y', '55y', '53m']

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!