web-dev-qa-db-ja.com

TypeError:Unicodeへの強制:文字列またはバッファが必要、intが見つかりました

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
25
Marks Gniteckis

この問題は、ここで文字列に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

37
TravelingMaker

次のように、各行に「%s」%と()を追加する必要があります。

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