2014-12-03 28 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

相关问题