Python: IndexError: list index out of range: Unable to figure out issue

Python: IndexError: list index out of range: Unable to figure out issue

string= "1110 Boston Road\nBronx, NY 10456\n(40.8276026690005, -73.90447525699966)"

我想从上面的字符串中提取值 -73.90447525699966。

代码:

coordinates=re.findall("\(.+\)",string)
lat=string[0].split(",")[1].replace(")","").strip()

Error: IndexError: list index out of range

当我用类似的函数(如下所述)提取值 40.8276026690005 时,它工作正常。

coordinates=re.findall("\(.+\)",string)
lat=coordinates[0].split(',')[0].replace('(','')

请帮忙。

使用不捕获括号的正则表达式,然后解包成变量非常简单:

coordinates = re.search('\((.+)\)', string).group(1)
lat, long = (float(c.strip()) for c in coordinates.split(','))

给出:

>>> lat
40.8276026690005
>>> long
-73.90447525699966