TypeError:强制转换为Unicode:需要字符串或缓冲区,找到int

时间:2014-12-03 14:52:26

标签: python api unicode buffer typeerror

我有2个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

2 个答案:

答案 0 :(得分:37)

问题可能与您在此处向字符串添加内容的事实有关

    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&gt; 3.0

答案 1 :(得分:1)

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

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