类型错误:强制使用Unicode:需要字符串或缓冲区,找到int

2024-06-02 18:29:51 发布

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

我有两个API。我正在从他们那里获取数据。我想把特定的代码部分分配给字符串,这样在编写代码时生活变得更轻松。代码如下:

import urllib2
import json

urlIncomeStatement = 'http://dev.c0l.in:8888'
apiIncomeStatement = urllib2.urlopen(urlIncomeStatement)
dataIncomeStatement = json.load(apiIncomeStatement)

urlFinancialPosition = 'http://dev.c0l.in:9999'
apiFinancialPosition = urllib2.urlopen(urlFinancialPosition)
dataFinancialPositiont = json.load(apiFinancialPosition)

for item in dataIncomeStatement:
    name = item['company']['name']
    interestPayable = int(item['company']['interest_payable'])
    interestReceivable = int(item['company']['interest_receivable'])
    sales = int(item['company']['interest_receivable'])
    expenses = int(item['company']['expenses'])
    openingStock = int(item['company']['opening_stock'])
    closingStock = int(item['company']['closing_stock'])
    sum1 = sales + expenses

    if item['sector'] == 'technology':
        name + "'s interest payable - " + interestPayable
        name + "'s interest receivable - " + interestReceivable
        name + "'s interest receivable - " + sales
        name + "'s interest receivable - " + expenses
        name + "'s interest receivable - " + openingStock
        name + "'s interest receivable - " + closingStock

print sum1

结果我得到:

Traceback (most recent call last):
  File "C:/Users/gnite_000/Desktop/test.py", line 25, in <module>
    name + "'s interest payable - " + interestPayable
TypeError: coercing to Unicode: need string or buffer, int found

Tags: 代码nameinimportjsonurllib2itemcompany
2条回答

问题可能与您在这里向字符串添加int有关

    if item['sector'] == 'technology':
        name + "'s interest payable - " + interestPayable
        name + "'s interest receivable - " + interestReceivable
        name + "'s interest receivable - " + sales
        name + "'s interest receivable - " + expenses
        name + "'s interest receivable - " + openingStock
        name + "'s interest receivable - " + closingStock

据我所知,解释程序不能隐式地将int转换为字符串。 不过,这可能管用

       str(name) + "'s interest receivable - " + str(closingStock)

在此基础上,我假设Python>;3.0

必须在每行中添加%s%和(),如下所示:

'%s' % (name + "'s interest payable - " + interestPayable)

相关问题 更多 >