python中字符串的真值 [英] Truth value of a string in python
问题描述
if <boolean> :
# do this
布尔值必须为 True 或 False.
boolean has to be either True or False.
那为什么
if "poi":
print "yes"
输出:是的
我不明白为什么是打印,因为poi"是真或假.
i didn't get why yes is printing , since "poi" is nether True or False.
推荐答案
当表达式需要布尔值时,Python 将尽最大努力评估该表达式的真实性".
Python will do its best to evaluate the "truthiness" of an expression when a boolean value is needed from that expression.
字符串的规则是空字符串被认为是False
,非空字符串被认为是True
.同样的规则也适用于其他容器,因此空字典或列表被视为 False
,包含一个或多个条目的字典或列表被视为 True
.
The rule for strings is that an empty string is considered False
, a non-empty string is considered True
. The same rule is imposed on other containers, so an empty dictionary or list is considered False
, a dictionary or list with one or more entries is considered True
.
None
对象也被认为是错误的.
The None
object is also considered false.
0
的数值被认为是假的(尽管 '0'
的字符串值被认为是真).
A numerical value of 0
is considered false (although a string value of '0'
is considered true).
所有其他表达式都被视为 True
.
All other expressions are considered True
.
详细信息(包括用户定义的类型如何指定真实性)可以在这里找到:http://docs.python.org/release/2.5.2/lib/truth.html.
Details (including how user-defined types can specify truthiness) can be found here: http://docs.python.org/release/2.5.2/lib/truth.html.
这篇关于python中字符串的真值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!