2014-12-03 49 views
19

我有2個API。我從他們那裏獲取數據。我想將特定的代碼部分分配給字符串,以便在編碼時使生活變得更容易。下面是代碼:TypeError:強制轉換爲Unicode:需要字符串或緩衝區,發現int找到

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 
+0

你可以包括完整的追溯? – selllikesybok 2014-12-03 14:55:17

+0

肯定的:' 回溯(最近通話最後一個): 文件 「C:/Users/gnite_000/Desktop/test.py」 25行,在 名+ 「的應付利息 - 」 + interestPayable 類型錯誤:強制爲Unicode:需要字符串或緩衝區,int找到 ' – 2014-12-03 14:57:18

+0

爲什麼你要做所有'name +'的interest interest - '+'語句?他們會被扔在當前的代碼中。 – selllikesybok 2014-12-03 15:03:15

回答

26

問題可能要做的事實,你將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

+0

如果我將刪除int(),我會得到相同的錯誤,但是,而不是在找到,我會得到浮動 – 2014-12-03 14:59:41

+0

@MarksGniteckis是的,因爲在序列化的對象中,你指向的數據是一個浮點數,而不是一個字符串。您將其轉換爲int,然後添加到字符串中。 float和int都不能添加到字符串中。只需將它們包裝在str()中,就像'+ str(interestPayable)'一樣。 – selllikesybok 2014-12-03 15:01:24

+0

好的,爲問題添加了不同的解決方案。賣什麼賣東西? – TravelingMaker 2014-12-03 15:01:59

2

您必須添加 '%s' 的%和(),以每行,像這樣:

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

這不適合我。 – FredFury 2015-12-14 09:08:48

相關問題