Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Search for a partial string in a list of strings

I have a list of strings looking like this:

['MEASUREMENT   K02313  New York',\
 'MEASUREMENT   K02338  London [BC:2.7.7.7]',\
 'MEASUREMENT   K14761  Kairo [BC:1.2.-.-]',\
 'MEASUREMENT   K03629  Berlin',\
 'MEASUREMENT   K02470  Paris [BC:5.6.2.-]',\
 'MEASUREMENT   K02469  Madrid [BC:5.43.2.2]',\
....]

As you can see some elements in the list have a string with the format BC:x.x.x.x, with x either being a number from 0-999 or a hyphen ("-").
Now I want to get a seperate list that has all of these BC:x.x.x.x elements saved.
I tried using a regular expression:

re.findall(r"BC:([0-9]|[1-9][0-9]|[1-9][0-9][0-9]|-).([0-9]|[1-9][0-9]|[1-9][0-9][0-9]|-).([0-9]|[1-9][0-9]|[1-9][0-9][0-9]|-).([0-9]|[1-9][0-9]|[1-9][0-9][0-9]|-)", list_name)

but it doesn’t work, I get the following error message:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

TypeError: expected string or bytes-like object

>Solution :

Your code doesn’t work because you’re currently passing a tuple of strings to the re.findall method. If you want to use a single command, then transform your tuple of strings into a single string:

re.findall(r"BC:[\d\.]+", ' '.join(list_name))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading