问题描述
我正在从文件中读取 True - False
值,我需要将其转换为布尔值.目前它总是将其转换为 True
,即使该值设置为 False
.
I'm reading a True - False
value from a file and I need to convert it to boolean. Currently it always converts it to True
even if the value is set to False
.
这是我正在尝试做的 MWE
:
Here's a MWE
of what I'm trying to do:
with open('file.dat', mode="r") as f:
for line in f:
reader = line.split()
# Convert to boolean <-- Not working?
flag = bool(reader[0])
if flag:
print 'flag == True'
else:
print 'flag == False'
file.dat
文件基本上由一个字符串组成,其中写入值 True
或 False
.这种安排看起来非常复杂,因为这是来自更大代码的最小示例,这就是我将参数读入其中的方式.
The file.dat
file basically consists of a single string with the value True
or False
written inside. The arrangement looks very convoluted because this is a minimal example from a much larger code and this is how I read parameters into it.
为什么flag
总是转换成True
?
推荐答案
bool('True')
和 bool('False')
总是返回 True
因为字符串 'True' 和 'False' 不为空.
bool('True')
and bool('False')
always return True
because strings 'True' and 'False' are not empty.
引用一位伟人(和 Python 文档):
To quote a great man (and Python documentation):
可以测试任何对象的真值,用于 if 或 while条件或作为以下布尔运算的操作数.这以下值被认为是错误的:
5.1.TruthValueTesting
Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:
- …
- 任何数字类型的零,例如,
0
、0L
、0.0
、0j
.李> - 任何空序列,例如,
''
、()
、[]
. - …
所有其他值都被认为是 true —所以很多类型的对象总是正确的.
All other values are considered true — so objects of many types are always true.
内置 bool
函数使用标准的真值测试程序.这就是为什么你总是得到 True
.
要将字符串转换为布尔值,您需要执行以下操作:
To convert a string to boolean you need to do something like this:
def str_to_bool(s):
if s == 'True':
return True
elif s == 'False':
return False
else:
raise ValueError # evil ValueError that doesn't tell you what the wrong value was
这篇关于将从文件读取的 True/False 值转换为布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!