ValueError:无法将字符串转换为float:“r”

2024-10-01 09:37:27 发布

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

所以我在读取一个文件,并将其存储在变量中,当它到达以下行时:

valP=float(listEleVP)

它返回这个:

^{pr2}$

这是整个代码:

def main():
    inFile=open('3weightcalc.in','r')
    i=0
    for line in inFile.readlines():
        a=line.split()

        for items in a:
            listEleVP=items[1]
            listEleVS=items[3]
            valP=float(listEleVP)
            valS=float(listEleVS)
            FinVal=float(valP*valS)
            txtA=items [0]
            txtB=items [2]
            print("On ",txtB,txtA,"would weigh ",FinVal,"pounds.")
    inFile.close()
main()

这是输入(.in)文件数据:

Fred 179.0 Luna 0.1654
Layla 131 Mars 0.376
Pat 145.2 Neptune 1.14
END 0 0 0

Tags: 文件informainlineitemsfloatinfile
2条回答

我认为内在的环是不必要的:

def main():
    inFile=open('3weightcalc.in','r')
    i=0
    for line in inFile.readlines():
        items=line.split()

        listEleVP=items[1]
        listEleVS=items[3]
        valP=float(listEleVP)
        valS=float(listEleVS)
        FinVal=float(valP*valS)
        txtA=items [0]
        txtB=items [2]
        print("On ",txtB,txtA,"would weigh ",FinVal,"pounds.")
    inFile.close()
main()

问题是在内部cicle中,您迭代了split返回的字符串。在

希望这有帮助!在

>>> text = """Fred 179.0 Luna 0.1654
... Layla 131 Mars 0.376
... Pat 145.2 Neptune 1.14
... END 0 0 0"""
>>> for line in text.splitlines():
...     a = line.split()
...     for items in a:
...             print items[1], items[3]
... 
r d
7 .
u a
. 6
a l
3
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
IndexError: string index out of range

你应该这样做:

^{pr2}$

相关问题 更多 >