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

How to save all occurences of a substring to an array in Python

I want to save each value between "(" and ")" from the string "obs1" to an array.

obs1 = "3341 - SSS - ELO CRED - (48,00)

4526 - SSS

7837 - SSS - MASTER DEB - (25,00)

2830 - SSS - VISA CRED - (35,00)"

I use the function

def find_between( s, first, last ):
    try:
            start = s.index( first ) + len( first )
            end = s.index( last, start )
            return s[start:end]
    except ValueError:
        return ""

then print

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

print(find_between(obs1, "(", ")"))

which outputs

48,00

However, what I want to do is save the numbers

48,00
25,00
35,00

to an array, how do I do that?

>Solution :

You can use re.findall:

import re

obs1 = """3341 - SSS - ELO CRED - (48,00)

4526 - SSS

7837 - SSS - MASTER DEB - (25,00)

2830 - SSS - VISA CRED - (35,00)"""

output = re.findall(r"\((.*?)\)", obs1)
print(output) # ['48,00', '25,00', '35,00']
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