【问题标题】:Basic code producing TypeError产生 TypeError 的基本代码
【发布时间】:2018-11-13 06:56:24
【问题描述】:

所以,我希望这段代码让用户输入狗狗链地址,然后我得到那个地址的余额。当我执行这个我得到错误:

url = "https://dogechain.info/api/v1/address/balance/"+ a

错误:

TypeError: cannot concatenate 'str' and 'int' objects

代码:

import requests

def main():
    a = input("Address?")
    url = "https://dogechain.info/api/v1/address/balance/"+ a
    response = requests.get(url)
    bal = response.json()[0]["balance"]
    print("Balance:",bal)

main()

【问题讨论】:

  • url = "https://dogechain.info/api/v1/address/balance/{}".format(a)
  • 试试这个,a = str(input('Addresses?'))
  • 在 Python 2.x 中使用 raw_input() 而不是 input()。前者在输入的字符串上执行和eval(),因此可能会返回字符串值以外的其他内容。

标签: python python-2.x dogecoin-api


【解决方案1】:
url = "https://dogechain.info/api/v1/address/balance/" + str(a)

url = "https://dogechain.info/api/v1/address/balance/{}".format(a)

下面@Ryan O'Donnell 的评论解释了原因,谢谢。

【讨论】:

  • 这很好,但不能解释发生了什么。 OP,例外是告诉你这里到底发生了什么:你不能连接一个字符串和一个 int。最新版本的 Python 也允许您这样做: f"This is an int: {some_int}" 其中 some_int 是您的变量。
猜你喜欢
  • 2021-02-18
  • 2020-11-11
  • 2010-12-08
  • 1970-01-01
  • 2011-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多