By iterating on the string, how can I extract more indexes and the corresponding values?

Viewed 45

Given my string, I'm trying to extract only the numeric values, but with the index and find functions I can only extract the value 7.22. How do I pick up the other three numeric values after the symbol "=" ?

stringa="[(Mark=7.22, Paola=3.12) , (Mark=30.1, Paola=1.78)]"
for i in stringa:
    i=stringa.index("=")
    n=stringa[i+1:i+5]
    print(n)

As output I get 7.22 printed the number of times as long as the string length! I, on the other hand, need you to print out 7.22, 3.12, 30.1 and 1.78.

1 Answers
import re

print(re.findall("\d+\.\d+", "[(Mark=7.22, Paola=3.12) , (Mark=30.1, Paola=1.78)]"))

Output:

['7.22', '3.12', '30.1', '1.78']

If you need to convert to float

print(list(map(float, re.findall("\d+\.\d+", "[(Mark=7.22, Paola=3.12) , (Mark=30.1, Paola=1.78)]"))))

Output:

[7.22, 3.12, 30.1, 1.78]

If you want to save the result to a variable

x = list(map(float, re.findall("\d+\.\d+", "[(Mark=7.22, Paola=3.12) , (Mark=30.1, Paola=1.78)]")))
Related