简体   繁体   中英

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)']

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.

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, ie put them into tuples:

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

python Built-in function eval 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))

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM