从字符串中获取浮点值

2024-04-30 06:35:31 发布

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

我想用Python在Blender中制作一个对象编码器,从textdocument读取值(坐标),结构如下:

p(-9,-8,27)
p(-9,-23,27) 
p(-7,-24,63) 
p(-7,-11,63)

如何使'p('')'在代码中消失,以便int转换成功?在

到目前为止,我已经写了:

^{pr2}$

我得到的错误是:

ValueError: could not convert string to float: 'p'

Tags: 对象代码convertstring错误not编码器结构
2条回答

如果您知道它总是以p开头(以结尾),可以这样做:

for line in file:
    coords = [float(c) for c in line.strip()[2:-1].split(',')]
    mesh.verts.append(Blender.NMesh.Vert(*coords))

行[2:-1]是切片表示法,它跳过前2个字符和最后一个字符(这样"(p(x,y,z)"变成{})。然后,它被split()得到一个字符串数组["x", "y", "z"]。然后,“对于数组中的每个坐标,给我一个浮点(坐标)”将是“float(c)for c in line…”的英文翻译

str.replace()返回一个带有替换的字符串对象;words值不受影响。在

我将使用str.strip()从行中删除p和括号:

for line in file:
    if not line.startswith('p'):
        continue  # skip these lines
    words = line.strip('\np()').split(',')
    x, y, z = map(float, words)
    mesh.verts.append(Blender.NMesh.Vert(x, y, z))

这里我们跳过任何开头没有p的行,并且str.strip()从字符串的开始和结尾删除参数中找到的任何字符;因此,开始和结尾的任何p(和{}字符都将被删除(以及从文件中读取行时始终存在的新行):

^{pr2}$

相关问题 更多 >