如何将 Nonetype 转换为 int 或 string?

我得到了一个 Nonetypex它通常是一个数字但也可能是 None。我想用一个数除以它,但 Python 提出:

TypeError: int() argument must be a string or a number, not 'NoneType'

我该怎么解决这个问题?

374983 次浏览

TypeError仅在您尝试传递 int() None时出现(据我所知,这是唯一的 NoneType值)。我想说的是,你真正的目标不应该是将 NoneType转换成 intstr,而是要找出在哪里/为什么你得到 None,而不是一个数字,并要么修复它或处理的 None适当。

在尝试对其执行任何计算之前,您应该检查以确保该值为 没有Nothing:

my_value = None
if my_value is not None:
print int(my_value) / 2

Note: my_value was intentionally set to None to prove the code works and that the check is being performed.

int(value or 0)

在提供 Python 认为是 False的任何值时,这将使用0,例如 Nothing、0、[]、“”等。因为0是 False,所以您应该只使用0作为替代值(否则您会发现您的0变成了那个值)。

int(0 if value is None else value)

This replaces only None with 0. Since we are testing for None specifically, you can use some other value as the replacement.

如果忘记从函数返回一个值,就会发生这种情况: 它随后返回 Nothing。查看赋值给该变量的所有位置,并查看其中是否有函数调用,其中该函数缺少 return 语句。

在其中一条评论中,你说:

不知怎么的,我得到了一个 Nonetype 值,它应该是一个 int,但现在它是一个 Nonetype 对象

如果这是你的代码,找出当你期望一个数字时你是如何得到 None的,并阻止 那个的发生。

如果它是别人的代码,找出它给出 None的条件,并确定一个合理的值来使用它,使用通常的条件代码:

result = could_return_none(x)


if result is None:
result = DEFAULT_VALUE

甚至..。

if x == THING_THAT_RESULTS_IN_NONE:
result = DEFAULT_VALUE
else:
result = could_return_none(x) # But it won't return None, because we've restricted the domain.

There's no reason to automatically use 0 here — solutions that depend on the "false"-ness of None assume you will want this. The DEFAULT_VALUE (if it even exists) completely depends on your code's purpose.

处理这种情况的一种常见的“ Python”方法称为 EAFP,即“ 请求原谅比请求许可更容易”。这通常意味着编写假定一切正常的代码,然后用一个 try...except块包装它来处理问题(以防万一)。

下面是适用于您的问题的编码风格:

try:
my_value = int(my_value)
except TypeError:
my_value = 0  # or whatever you want to do


answer = my_value / divisor

或者更简单、更快一些:

try:
answer = int(my_value) / divisor
except TypeError:
answer = 0

相反,更传统的方法被称为 LBYL,它代表的是“ 三思而后行”,这是@Scottish 和其他一些人所建议的。关于这个主题的其他报道,请参阅我的 answer和相关的评论,对于问题 确定关键字是否在 dictionary 中,请参阅本网站的其他地方。

EAFP的一个潜在问题是,它可以隐藏您正在使用的代码或第三方模块的其他部分出错的事实,特别是当异常频繁发生时(因此根本不是真正的“异常”情况)。

我在使用 python 电子邮件功能时遇到了同样的问题。 下面是我试图将电子邮件主题检索到一个变量中的代码。这对于大多数电子邮件和变量填充来说工作得很好。如果你收到一封来自雅虎或类似的邮件,发件人没有填写主题行,雅虎不会在邮件中创建一个主题行,你会得到一个从函数返回的 NoneType。马蒂诺和苏联人一样给出了正确的答案。IMO 苏维埃的回答从编程的角度来看更为简洁,而不一定是从 Python 的角度来看。 下面是一些展示该技术的代码:

import sys, email, email.Utils


afile = open(sys.argv[1], 'r')
m = email.message_from_file(afile)
subject = m["subject"]


# Soviut's Concise test for unset variable.


if subject is None:
subject = "[NO SUBJECT]"


# Alternative way to test for No Subject created in email (Thanks for NoneThing Yahoo!)


try:
if len(subject) == 0:
subject = "[NO SUBJECT]"


except TypeError:
subject = "[NO SUBJECT]"


print subject


afile.close()

对于这种类型的错误,我已经成功地使用了 int (x 或0) ,只要在逻辑中 Nothing 应该等于0。 Note that this will also resolve to 0 in other cases where testing x returns False. e.g. empty list, set, dictionary or zero length string. 抱歉,金德尔已经回答过了。

在某些情况下,使用一个函数将 Nothing 转换为 int 0是有帮助的:

def nz(value):


'''
Convert None to int zero else return value.
'''


if value == None:
return 0
return value

在 Python 3中,你也可以使用“ or”关键字:

foo = bar or 0
foo2 = bar or ""