简体   繁体   English

python条件检查中的str(None)

[英]str(None) in python condition checks

Say I have a variable in python a假设我在 python 中有一个变量a

if a is None , then is str(None) going to return None or something else?如果aNone ,那么str(None)会返回None还是其他什么?

I ran this in an intepreter an did something like:我在一个解释器中运行了这个并做了一些类似的事情:

a = str(None)
print(a is None)

And it printed False , why is that?它打印了False ,这是为什么?

In Python, str will always return a string.在 Python 中, str始终返回一个字符串。 In this case, str(None) is the string "None" .在这种情况下, str(None)是字符串"None" "None" is not equal to None since one is a string and the other is the actual value. "None"不等于None因为一个是字符串,另一个是实际值。

With regard to your first question (you should have only one per post, by the way), you can figure this out by running it yourself.关于您的第一个问题(顺便说一下,每个帖子应该只有一个),您可以通过自己运行来解决这个问题。

With regard to your second question, you are printing the value of the expression a is None .关于您的第二个问题,您正在打印表达式a is None的值。 a is either None or it isn't. a要么是None要么不是。 Either way, you'll get a Boolean value.无论哪种方式,您都会得到一个布尔值。 In this case, a isn't None but rather a string.在这种情况下, a不是None而是一个字符串。

Converting it to a string is changing it to the word "None".将其转换为字符串就是将其更改为“无”一词。 Try the below.试试下面的。

a = str(None)
print(type(a))
print(type(None))
print('None' == None)

This will output the below.这将输出以下内容。

<class 'str'>
<class 'NoneType'>
False

A string and a NoneType are not equal.字符串和 NoneType 不相等。

Maybe you need to print out the result of a, and then you know why the result is False .也许你需要打印出 a 的结果,然后你就知道为什么结果是False

a = str(None)
print(type(a))
print(a is None)

The operator is is an identity operator, meaning that it returns True if both variables are the same object.运算符is是一个身份运算符,这意味着如果两个变量是同一个对象,则它返回True Objects referencing None will always have the same identity, however, str(None) and None will not have the same identity, therefore your print statement returns False .引用None对象将始终具有相同的标识,但是, str(None)None将不具有相同的标识,因此您的打印语句返回False

The is operator has nothing to do with whether something is equal in value, you have to use == operator for that. is运算符与值是否相等无关,您必须为此使用==运算符。 See examples below.请参阅下面的示例。

a = str(None)

>>>print(a == None)
False
>>> print(a is None)
False
>>> print(a is str(None))
False
>>> print(a == str(None))
True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM