我需要将一个字符串分成三个值 (x,y,z) 字符串是这样的 (48,25,19)
我使用了"re.findall",它工作正常,但有时会产生这个错误
(plane_X, plane_Y, plane_Z = re.findall("\d+.\d+", planepos)
ValueError:没有足够的值来解压(预期 3,得到 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 因此,如果有人知道更好的方法或如何解决此错误,我们将不胜感激。
请您参考如下方法:
您的正则表达式仅适用于带小数点的数字,不适用于整数,因此会出现错误。您可以改为去除括号和空格的字符串,然后用逗号分隔字符串,并将生成的字符串序列映射到 float 构造函数:
x, y, z = map(float, planepos.strip('() \n').split(','))
