Python 如何将 Nonetype 转换为 int 或 string?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3930188/
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
How to convert Nonetype to int or string?
提问by user469652
I've got an Nonetypevalue x, it's generally a number, but could be None. I want to divide it by a number, but Python raises:
我有一个Nonetypevalue x,它通常是一个数字,但也可能是None。我想将它除以一个数字,但 Python 提出:
TypeError: int() argument must be a string or a number, not 'NoneType'
How can I solve this?
我该如何解决这个问题?
采纳答案by detly
In one of the comments, you say:
在其中一条评论中,您说:
Somehow I got an Nonetype value, it supposed to be an int, but it's now a Nonetype object
不知何故我得到了一个 Nonetype 值,它应该是一个 int,但它现在是一个 Nonetype 对象
If it's your code, figure out how you're getting Nonewhen you expect a number and stop thatfrom happening.
如果这是您的代码,请弄清楚None当您期望一个数字时您会得到什么并阻止它发生。
If it's someone else's code, find out the conditions under which it gives Noneand determine a sensible value to use for that, with the usual conditional code:
如果是别人的代码,找出它给出的条件None并确定一个合理的值,使用通常的条件代码:
result = could_return_none(x)
if result is None:
result = DEFAULT_VALUE
...or even...
...甚至...
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 0here — solutions that depend on the "false"-ness of Noneassume you will want this. The DEFAULT_VALUE(if it even exists) completely depends on your code's purpose.
没有理由在0这里自动使用——依赖于“假”的解决方案,None你会想要这个。的DEFAULT_VALUE(如果存在的话)完全取决于你的代码的目的。
回答by waffle paradox
That TypeErroronly appears when you try to pass int()None(which is the only NoneTypevalue, as far as I know). I would say that your real goal should not be to convert NoneTypeto intor str, but to figure out where/why you're getting Noneinstead of a number as expected, and either fix it or handle the Noneproperly.
这TypeError仅当您尝试通过出现int()None(这是唯一的NoneType价值,因为据我所知)。我会说你的真正目标不应该是转换NoneType为intor str,而是要弄清楚你在哪里/为什么得到None而不是预期的数字,然后修复它或None正确处理它。
回答by Soviut
You should check to make sure the value is notNone before trying to perform any calculations on it:
在尝试对其执行任何计算之前,您应该检查以确保该值不是None:
my_value = None
if my_value is not None:
print int(my_value) / 2
Note:my_valuewas intentionally set to None to prove the code works and that the check is being performed.
注意:my_value有意设置为 None 以证明代码有效并且正在执行检查。
回答by kindall
int(value or 0)
This will use 0 in the case when you provide any value that Python considers False, such as None, 0, [], "", etc. Since 0 is False, you should only use 0 as the alternative value (otherwise you will find your 0s turning into that value).
如果您提供 Python 考虑的任何值False,例如 None、0、[]、"" 等,这将使用 0。由于 0 是False,您应该只使用 0 作为替代值(否则您会发现您的 0变成那个值)。
int(0 if value is None else value)
This replaces only Nonewith 0. Since we are testing for Nonespecifically, you can use some other value as the replacement.
这仅替换None为 0。由于我们正在None专门测试,因此您可以使用其他一些值作为替换。
回答by Jouni K. Sepp?nen
This can happen if you forget to return a value from a function: it then returns None. Look at all places where you are assigning to that variable, and see if one of them is a function call where the function lacks a return statement.
如果您忘记从函数中返回一个值,就会发生这种情况:然后它返回 None。查看您分配给该变量的所有位置,并查看其中一个是函数调用,该函数缺少 return 语句。
回答by martineau
A common "Pythonic" way to handle this kind of situation is known as EAFPfor "It's easier to ask forgiveness than permission". Which usually means writing code that assumes everything is fine, but then wrapping it with a try..exceptblock just in case to handle things when it's not.
处理这种情况的一种常见的“Pythonic”方式被称为EAFP,因为“请求宽恕比许可更容易”。这通常意味着编写假设一切都很好的代码,然后用一个try..except块包装它,以防万一在它不是的时候处理事情。
Here's that coding style applied to your problem:
这是适用于您的问题的编码风格:
try:
my_value = int(my_value)
except TypeError:
my_value = 0 # or whatever you want to do
answer = my_value / divisor
Or perhaps the even simpler and slightly faster:
或者也许更简单,稍微快一点:
try:
answer = int(my_value) / divisor
except TypeError:
answer = 0
The inverse and more traditional approach is known as LBYLwhich stands for "Look before you leap" is what @Soviut and some of the others have suggested. For additional coverage of this topic see my answerand associated comments to the question Determine whether a key is present in a dictionaryelsewhere on this site.
反向和更传统的方法被称为LBYL,它代表“跳前先看”,这是@Soviut 和其他一些人所建议的。有关此主题的更多报道,请参阅我对“确定关键字是否存在于本站点其他地方的字典中”问题的回答和相关评论。
One potential problem with EAFPis that it can hide the fact that something is wrong with some other part of your code or third-party module you're using, especially when the exceptions frequently occur (and therefore aren't really "exceptional" cases at all).
EAFP 的一个潜在问题是它可以隐藏您的代码的其他部分或您正在使用的第三方模块出现问题的事实,特别是当异常频繁发生时(因此并不是真正的“例外”情况)一点)。
回答by George Pearson
I was having the same problem using the python email functions. Below is the code I was trying to retrieve email subject into a variable. This works fine for most emails and the variable populates. If you receive an email from Yahoo or the like and the sender did no fill out the subject line Yahoo does not create a subject line in the email and you get a NoneType returned from the function. Martineau provided a correct answer as well as Soviut. IMO Soviut's answer is more concise from a programming stand point; not necessarily from a Python one. Here is some code to show the technique:
我在使用 python 电子邮件功能时遇到了同样的问题。下面是我试图将电子邮件主题检索到变量中的代码。这适用于大多数电子邮件和变量填充。如果您收到来自 Yahoo 或类似机构的电子邮件并且发件人没有填写主题行,则 Yahoo 不会在电子邮件中创建主题行,并且您会从该函数返回 NoneType。Martineau 和 Soviut 都提供了正确的答案。从编程的角度来看,IMO Soviut 的回答更简洁;不一定来自 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()
回答by user3109122
I've successfully used int(x or 0) for this type of error, so long as None should equate to 0 in the logic. 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. Sorry, Kindall already gave this answer.
我已经成功地将 int(x or 0) 用于这种类型的错误,只要在逻辑中 None 应该等于 0 。请注意,在测试 x 返回 False 的其他情况下,这也将解析为 0。例如空列表、集合、字典或零长度字符串。抱歉,Kindall 已经给出了这个答案。
回答by user2920482
In some situations it is helpful to have a function to convert None to int zero:
在某些情况下,有一个函数将 None 转换为 int 零是有帮助的:
def nz(value):
'''
Convert None to int zero else return value.
'''
if value == None:
return 0
return value
回答by Ferrarezi
In Python 3 you can use the "or" keyword too. This way:
在 Python 3 中,您也可以使用“or”关键字。这边走:
foo = bar or 0
foo2 = bar or ""

