无法将字符串转换为浮点数:price [0] - python

问题描述:

我想制作一个货币转换器,它将采用雅虎当前的汇率,并将其乘以用户需要的金额。但我无法将它们相乘。你可以帮我吗?无法将字符串转换为浮点数:price [0] - python

我总是得到: 回溯(最近通话最后一个):文件 “C:\用户\扬\桌面\ c.py” 17行,在realprice =浮动( “价格[0]”)

import urllib 
 
import re 
 

 
stocklist = ["eurusd"] 
 

 
i=0 
 
while i<len(stocklist): 
 
    url = "http://finance.yahoo.com/q?s=eurusd=X" 
 
    htmlfile = urllib.urlopen(url) 
 
    htmltext = htmlfile.read() 
 
    regex = '<span id="yfs_l10_eurusd=x">(.+?)</span>' 
 
    pattern = re.compile(regex) 
 
    price = re.findall(pattern,htmltext) 
 
    print "the price of", stocklist[i],"is" ,price[0] 
 
    i+=1 
 

 
realprice = float("price[0]") 
 

 
print ("Currency Exchange") 
 
ex = raw_input("A-Euro to Dollars, B-Dollars to Euro") 
 
if ex == "A": 
 
    ptd = int(raw_input("How much would you like to convert: ")) 
 
    f = ptd*price[0] 
 
    print("It is $",f) 
 
if ex == "B": 
 
    ptd = float(raw_input("How much would you like to convert")) 
 
    f = ptd*0.7 
 
    f2 = round(f,2) 
 
    print ("It is $",f2)

ValueError异常:无法将字符串转换为float:价格[0]

python code

+1

如果你想访问price'的'的第一个元素,那么你会使用'realprice =浮动(价格[0] )' – Jkdc

的问题是在这条线:

realprice = float("price[0]") 

你所要做的是与非数字字符的字符串转换为浮动不工作。

更准确地说,您正在将price[0]转换为数字。

要解决这个问题,只需删除上面一行中的"字符。就像这样:

realprice = float(price[0]) 

(期望的编辑,因为你有几个错误)