Python 连接“str”和“NoneType”对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27980579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:33:47  来源:igfitidea点击:

Concatenate 'str' and 'NoneType' objects

pythonpython-2.x

提问by jarmouz

I try to stock string in my database with python script. But but when running the code I have this error cannot concatenate 'str' and 'NoneType' objects.

我尝试使用 python 脚本在我的数据库中存储字符串。但是,但是在运行代码时,我遇到此错误无法连接 'str' 和 'NoneType' 对象。

How can i decode this string "Poste Si\xe8ge" to be stocked successfully

我如何解码这个字符串“Poste Si\xe8ge”才能成功入库

    insert="INSERT INTO blacklist VALUES(INET_ATON('"+ long2ip(row[0]) +"'),NOW(),'"+ check.country +"',4,' ','"+detect[0]+"','"+ispTarget[0]+"')"

detect[0]=Poste Si\xe8ge

TypeError: cannot concatenate 'str' and 'NoneType' objects

Help me plz

请帮帮我

回答by poke

TypeError: cannot concatenate 'str' and 'NoneType' objects

类型错误:无法连接“str”和“NoneType”对象

This error actually describes very well what is happening: You are trying to concatenate a string with something else which happens to be None. For example:

这个错误实际上很好地描述了正在发生的事情:您正在尝试将一个字符串与其他恰好是None. 例如:

>>> 'foo' + None
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    'foo' + None
TypeError: cannot concatenate 'str' and 'NoneType' objects

Of course, you probably don't try to concatenate Noneexplicitely but you have some variable instead, e.g. 'foo' + bar. Now this means that baris actually None, so the concatenation fails.

当然,您可能不会尝试None显式连接,而是有一些变量,例如'foo' + bar. 现在这意味着bar实际上是None,因此连接失败。

In your case, you are concatenating the values long2ip(row[0]), check.country, detect[0], and ispTarget[0]with the string. So at least one of those is None. So check these values and make sure that none of them is None(for example make sure long2ipactually returnsa value). And then it should work fine.

在您的情况下,您将值long2ip(row[0]), check.country, detect[0], 和ispTarget[0]与字符串连接起来。所以至少其中之一是None. 所以检查这些值并确保它们都不是None(例如确保long2ip实际返回一个值)。然后它应该可以正常工作。

回答by M.A Majid

Did you try str()in-built function.?

您是否尝试str()过内置功能。?

If you concatenate string objects with other data types, then the other type has to be converted to str(other_data_type)

如果将字符串对象与其他数据类型连接起来,则必须将其他类型转换为 str(other_data_type)

Hope this helps you.

希望这对你有帮助。