python if语句失败

问题描述 投票:0回答:1

我试图检查一个简单的标志是真还是假,但我的IF语句失败,它没有给我正确的结果,希望有人可以提供帮助!

我正在使用(在python3.6中)这个url

    https://bittrex.com/api/v1.1/public/getticker?market=usdt-btc

对于get请求,它应返回的数据如下所示(来自浏览器中的URL):

    {"success":true,"message":"","result":{"Bid":18362.00000000,"Ask":18399.00000000,"Last":18362.00000000}}

这是我的计划:

    import sys
    import time
    import requests
    import json
    import os

    BTCtick = 'https://bittrex.com/api/v1.1/public/getticker?market=usdt-btc'
    reqBTC = requests.get('https://bittrex.com/api/v1.1/public/getticker?        market=usdt-btc').text
    BTCdata = json.loads(reqBTC)

    testResult = BTCdata['success']
    print("=============================")
    print("success content: ", BTCdata['success'])
    if (testResult == 'True'):
        print("IF: success flag is TRUE")
    else:
        print("IF: success flag is FALSE")
    print("=============================")

    print("result content: ", BTCdata['result'])
    print("Bid: ", BTCdata['result'] ['Bid'], sep='')
    print("Ask: ", BTCdata['result'] ['Ask'], sep='')
    print("Last: ", BTCdata['result'] ['Last'], sep='')
    print("=============================")
    exit()

控制台中的输出如下所示:

    =============================
    success content:  True
    IF: success flag is FALSE
    =============================
    result content:  {'Bid': 18420.0, 'Ask': 18439.99999999, 'Last': 18439.99999999}
    Bid: 18420.0
    Ask: 18439.99999999
    Last: 18439.99999999
    =============================

知道我在这里缺少什么吗?我敢肯定这很简单请帮助我,我对python有些新意见并找到了什么问题,过去两天我一直在阅读很多,但找不到问题!

python python-3.x parsing if-statement
1个回答
2
投票

json.loads()会将true转换为Python的布尔Trueconversion table for the reference)。你只需要检查testResult值的真实性,而不是将它与字符串'True'进行比较:

if testResult:
    print("IF: success flag is TRUE")
else:
    print("IF: success flag is FALSE")

换句话说,这是你将testResult'True'字符串进行比较时发生的事情:

In [1]: testResult = True

In [2]: testResult == 'True'
Out[2]: False
© www.soinside.com 2019 - 2024. All rights reserved.