使用“re.findall”拆分字符串时出错

2024-09-27 23:21:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要把一个字符串分成三个值(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 因此,如果有人知道一个更好的方法来做这件事,或如何解决这个错误将不胜感激


Tags: 字符串testre错误testsopencsfile
3条回答

可以使用ast.literal_eval安全地计算字符串:

import ast

s = '(48,25,19)'
x, y, z = ast.literal_eval(s)

# x => 48
# y => 25
# z => 19

如果您的数字是整数,则可以使用正则表达式:

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

正则表达式只适用于带小数点的数字,而不适用于整数,因此会出现错误。您可以将字符串中的括号和空格去掉,然后用逗号拆分字符串,并将结果字符串序列映射到float构造函数:

x, y, z = map(float, planepos.strip('() \n').split(','))

相关问题 更多 >

    热门问题