Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JSON Python、字符串到浮点转换或操作数。API数据_Json_Python 3.x - Fatal编程技术网

JSON Python、字符串到浮点转换或操作数。API数据

JSON Python、字符串到浮点转换或操作数。API数据,json,python-3.x,Json,Python 3.x,我希望将JSON数据更改为浮点数,以便计算比特币的价格,以便继续进行其他计算 我已经做了大量的计算方法,如果我用int或float替换currency变量,效果会很好 只有当我从api获取json数据时,我才会遇到问题 我收到了以下错误消息 e_b = float(btc) / float(cur) TypeError: unsupported operand type(s) for /: 'float' and 'str' 简单地 e_b = btc / cur 我明白了 这是问题代码

我希望将JSON数据更改为浮点数,以便计算比特币的价格,以便继续进行其他计算

我已经做了大量的计算方法,如果我用int或float替换currency变量,效果会很好

只有当我从api获取json数据时,我才会遇到问题

我收到了以下错误消息

e_b = float(btc) / float(cur)

TypeError: unsupported operand type(s) for /: 'float' and 'str'
简单地

 e_b = btc / cur
我明白了

这是问题代码。如果给定浮点或int,那么之后一切都会正常运行

import requests
import json

cur_price_url = "http://api.coindesk.com/v1/bpi/currentprice.json"

def bitcoin_current_price(url):
    """
        Function to return json data from API
        “Powered by CoinDesk” http://www.coindesk.com/price/
    """
    return requests.get(url).json()
btc_price = (bitcoin_current_price(cur_price_url))

def btc_cur():
    """  Displays Different Currency Rates and Information """
    print('\n\n USD: ' + str(btc_price['bpi']['USD']['rate']))
    print('\n\n EUR: ' + str(btc_price['bpi']['EUR']['rate']))
    print('\n\n GBP: ' + str(btc_price['bpi']['GBP']['rate']))
btc_cur()

bitcoin_usd = str(btc_price['bpi']['USD']['rate'])
bitcoin_eur = str(btc_price['bpi']['USD']['rate'])
bitcoin_gbp = str(btc_price['bpi']['USD']['rate'])

btc = 1
currency = 123.32
amount = 1

def cur_name():
    """ Name the Currencies """
    if currency == bitcoin_usd:
        cur_prt = "USD"
    elif currency == bitcoin_gbp:
        cur_prt = "GBP"
    else:
        cur_prt = "EUR"
    return cur_prt

def convert(cur, num):
    """simple conversion between currencies"""
    e_b = btc / cur
    print('\n' + str(1) + " " + str(cur_name()) + " is " + str(e_b) + " BTC")
    print(str(1) + " BTC" + " is " + str(cur) + ' ' + str(cur_name()) + '\n')

    e_b_con = e_b * num
    return e_b_con

print(convert(currency, amount))

cur=2541.6300
的值不是有效的浮点数,因此Python无法自动转换它。您必须将其更改为
xxx.yy

以下是一种方法:

e_b = btc / float(cur.replace(",",""))

让我高兴的是这些简单的事情!
e_b = btc / float(cur.replace(",",""))