G-71
G-71

Reputation: 3682

Parsing numbers of integer and real type in string

I have got a list of strings of the following format:

[ "%AB0.1.100", "%TB4.1.15" ]

How i can parse this strings, that a i'd like to take for 1st element of list "0.1" of real type and "100" of integer type and "4.1" of real type and "15" of integer type.

How i can do this in loop ?

Upvotes: 1

Views: 148

Answers (3)

towi
towi

Reputation: 22267

I think I'd not use re for this one. I'd use slicing and split:

for elem in l:
    # elem: "%AB0.1.100"
    two = elem[3:]    # elem: "0.1.100"
    ps = two.split(".")
    assert len(ps) == 3
    # ps: "0" , "1", "100"
    f = float("%s.%s" % (ps[0],ps[1]))
    i = int(ps[2])

I think you can tweak this quite easily. Advantage of re: more flexible in the general case.

Upvotes: 0

gecco
gecco

Reputation: 18830

l = [ "%AB0.1.100", "%TB4.1.15" ]

for el in l:
  endOfFloat = el.rfind('.')
  f = float(el[3:endOfFloat])
  i = int(el[endOfFloat+1:])

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336128

>>> import re
>>> l = [ "%AB0.1.100", "%TB4.1.15" ]
>>> out = []
>>> for item in l:
...    m = re.search(r"(\d+\.\d+)\.(\d+)", item)
...    f = float(m.group(1))
...    i = int(m.group(2))
...    out.append((f, i))
...
>>> out
[(0.1, 100), (4.1, 15)]

Upvotes: 1

Related Questions