简单的字符串连接失败

时间:2015-03-29 15:32:27

标签: python python-2.7 string-concatenation yahoo-finance nonetype

我有以下代码:

from yahoo_finance import Currency

symbolslist  = ["EURUSD","EURGBP","EURJPY","EURRUB","USDCAD","USDCHF","AUSUSD"]

for i in range(len(symbolslist)):
        symbol = symbolslist[i]
        nomisma = Currency(symbol).get_rate()

        quota = symbol + " = " + nomisma
        print quota

我得到了结果:

EURUSD = 1.0891
EURGBP = 0.7322
EURJPY = 129.7440
EURRUB = 63.0560
USDCAD = 1.2614
USDCHF = 0.9622
Traceback (most recent call last):
  File "yahoopy.py", line 13, in <module>
    quota = symbol + " = " + nomisma
TypeError: cannot concatenate 'str' and 'NoneType' objects

我知道this链接已经讨论过这个错误。

但是我希望我能在不诉诸mysql的情况下克服这个错误。

2 个答案:

答案 0 :(得分:5)

问题是拼写错误。而不是AUDUSD你写了AUSUSD。修复它,错误将消失:

symbolslist  = ["EURUSD","EURGBP","EURJPY","EURRUB","USDCAD","USDCHF","AUDUSD"]

使用format作为@BhargavRao建议捕获此类错误仍然是一个好主意。

答案 1 :(得分:2)

在concat语句

上方添加if子句
if nomisma:
    quota = symbol + " = " + nomisma

假设 - 这意味着您的数据库中不存在AUSUSD,这就是Currency(symbol).get_rate()返回None的原因。同样如here所述,它是AUDUSD而不是AUSUSD

注意:最好使用format进行连接,如

quota = "{} = {}".format(symbol,nomisma)