我需要把一个字符串分成三个值(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 因此,如果有人知道一个更好的方法来做这件事,或如何解决这个错误将不胜感激
可以使用
ast.literal_eval
安全地计算字符串:如果您的数字是整数,则可以使用正则表达式:
如果存在混合数:
正则表达式只适用于带小数点的数字,而不适用于整数,因此会出现错误。您可以将字符串中的括号和空格去掉,然后用逗号拆分字符串,并将结果字符串序列映射到
float
构造函数:相关问题 更多 >
编程相关推荐