Tania
Tania

Reputation: 428

How to extract numbers from a string in python

I have a string of coordinates as follows

str='(707.027,949.189),(598.919,6.48649)'

I want to extract the values, but the parenthesis is getting hard to workaround. I tried the following:

str.split(",") which gives ['(707.027', '949.189)', '(598.919', '6.48649)']
str.split(",\(\)") which gives ['(707.027,949.189),(598.919,6.48649)']

Upvotes: 0

Views: 533

Answers (4)

Grismar
Grismar

Reputation: 31319

Although you could use an eval in this case, that's generally not a safe way of dealing with this type of data, especially if the string you're trying to interpret isn't in your code or entered by yourself.

Here's a solution with regex, as you requested:

import re

subject = '(707.027,949.189),(598.919,6.48649)'
match = re.search(r"\(([\d.]+),([\d.]+)\),\(([\d.]+),([\d.]+)\)", subject)

numbers = []
p1, p2 = tuple(), tuple()
if match:
    numbers = [float(match.group(n)) for n in range(1, 5)]
    # or
    p1 = (float(match.group(1)), float(match.group(2)))
    p2 = (float(match.group(3)), float(match.group(4)))

print(numbers, p1, p2)

Upvotes: 1

Derek Eden
Derek Eden

Reputation: 4618

given your string you could also use this more general purpose approach:

import re
s = '(707.027,949.189),(598.919,6.48649)'
nums = re.findall('\d*\.\d*',s)
nums #['707.027', '949.189', '598.919', '6.48649']

this strips out all the floats from any string..then you can do whatever you want with them, i.e. put them into tuples:

coords = list(zip(nums[::2],nums[1::2]))
coords #[('707.027', '949.189'), ('598.919', '6.48649')]

Upvotes: 2

libin
libin

Reputation: 457

python Built-in functioneval can do it, it parse a string into code.

>>> s = '(707.027,949.189),(598.919,6.48649)'
>>> eval(s)
((707.027, 949.189), (598.919, 6.48649))

Upvotes: 1

kaya3
kaya3

Reputation: 51037

Your string is a valid Python literal, so try ast.literal_eval:

>>> from ast import literal_eval
>>> s = '(707.027,949.189),(598.919,6.48649)'
>>> literal_eval(s)
((707.027, 949.189), (598.919, 6.48649))

This parses s as Python code and evaluates it (safely, as a literal value), resulting in a tuple of tuples.

Upvotes: 3

Related Questions