pistal
pistal

Reputation: 2456

extracting numbers from a string in a list via regex

I've a linear equation and i'm trying to process it in Python. This linear equation is in a list.

z=['i=(6040.66194238063)+(51.7296373326464*a)+(41.7319764455748*b)+(-193.993966414084*c)+(-215.670960526368*d)+(-531.841753178744*e)+(5047.1039987166*f)+(3925.37115184923*g)+(77.7712765761365*h)']

I want to find a way to build a list which contains all the constants.

Upvotes: 1

Views: 60

Answers (2)

timgeb
timgeb

Reputation: 78690

import re
m=re.findall('-?[0-9]+\.?[0-9]*', z[0])

will give you a list m:

['6040.66194238063', '51.7296373326464', '41.7319764455748', '-193.993966414084', '-215.670960526368', '-531.841753178744', '5047.1039987166', '3925.37115184923', '77.7712765761365']

If you want the list as a list of floating point numbers, you can now do:

m = [float(x) for x in m]

Upvotes: 2

daouzli
daouzli

Reputation: 15328

If you want to extract the constants in a list, the following should do the work:

z = ["i=(6040.66194238063)+(51.7296373326464*a)+(41.7319764455748*b)+(-193.993966414084*c)+(-215.670960526368*d)+(-531.841753178744*e)+(5047.1039987166*f)+(3925.37115184923*g)+(77.7712765761365*h)"]
for elem in z:
    num = ""
    cst = []
    for c in elem:
        if c.isdigit() or c =='.' or (c == '-' and not len(num)):
            num += c
        elif len(num):
            cst.append(num)
            num = ""
    print cst

This will output:

['6040.66194238063', '51.7296373326464', '41.7319764455748', '193.993966414084', '215.670960526368', '531.841753178744', '5047.1039987166', '3925.37115184923', '77.7712765761365']

Upvotes: 1

Related Questions