我需要将一个字符串分成三个值(x,y,z),该字符串类似于(48,25,19)
我使用了“ re.findall” ,它可以正常工作,但有时会产生此错误
(plane_X, plane_Y, plane_Z = re.findall("\d+.\d+", planepos)
ValueError: not enough values to unpack (expected 3, got 0))
这是代码:
def read_data():
# reading from file
file = open("D:/Cs/Grad/Tests/airplane test/Reading/Positions/PlanePos.txt", "r")
planepos = file.readline()
file.close()
file = open("D:/Cs/Grad/Tests/airplane test/Reading/Positions/AirportPosition.txt", "r")
airportpos = file.readline()
file.close()
# ==================================================================
# spliting and getting numbers
plane_X, plane_Y, plane_Z = re.findall("\d+\.\d+", planepos)
airport_X, airport_Y, airport_Z = re.findall("\d+\.\d+", airportpos)
return plane_X,plane_Y,plane_Z,airport_X,airport_Y,airport_Z
我需要的是分割字符串(48,25,19)到 x = 48,y = 25,z = 19 > 因此,如果有人知道更好的方法或解决此错误的方法,将不胜感激。
答案 0 :(得分:2)
您可以使用ast.literal_eval
安全地评估您的字符串:
import ast
s = '(48,25,19)'
x, y, z = ast.literal_eval(s)
# x => 48
# y => 25
# z => 19
答案 1 :(得分:2)
您的正则表达式仅适用于带小数点的数字,不适用于整数,因此会出错。您可以改为去除括号和空格的字符串,然后用逗号分隔该字符串,并将生成的字符串序列映射到float
构造函数:
x, y, z = map(float, planepos.strip('() \n').split(','))
答案 2 :(得分:1)
如果您的数字是整数,则可以使用正则表达式:
re.findall(r"\d+","(48,25,19)")
['48', '25', '19']
如果有混数:
re.findall(r"\d+(?:\.\d+)?","(48.2,25,19.1)")
['48.2', '25', '19.1']