Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match digits on a string with certain conditions in python

Tags:

python

I have a sequence of strings in the form

s1 = "Schblaum 12324 tunguska 24 234n"
s2 = "jacarta 331 matchika 22 234k"
s3 = "3239 thingolee 80394 234k"

and I need to separate those strings in two strings, just after the number on the middle of the string, ignoring if there is a number on the first part of the string. Something like

["Schblaum 12324", "tunguska 24 234n"]
["jacarta 331", "matchika 22 234k"]
["3239 thingolee 80394", "bb 6238"]

I tried to use regex in the form

finder = re.compile(""\D(\d+)\D"")
finder.search(s1)

to no avail. Is there a way to do it, maybe without using regex? Cheers!

EDIT: just found a case where the initial string is just

"jacarta 43453"

with no other parts. This should return

["jarcata 43453"]
like image 667
Ivan Avatar asked Dec 11 '25 23:12

Ivan


1 Answers

Use re.findall

>>> import re
>>> s1 = "Schblaum 12324 tunguska 24 234n"
>>> re.findall(r'^\S+\D*\d+|\S.*', s1)
['Schblaum 12324', 'tunguska 24 234n']
>>> s2 = "jacarta 331 matchika 22 234k"
>>> s3 = "3239 thingolee 80394 234k"
>>> re.findall(r'^\S+\D*\d+|\S.*', s2)
['jacarta 331', 'matchika 22 234k']
>>> re.findall(r'^\S+\D*\d+|\S.*', s3)
['3239 thingolee 80394', '234k']
like image 190
Avinash Raj Avatar answered Dec 13 '25 14:12

Avinash Raj



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!