Home > Software design >  How to save all occurences of a substring to an array in Python
How to save all occurences of a substring to an array in Python

Time:10-20

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

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?

CodePudding user response:

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']
  • Related