我正在从文件中读取 True - False
值,我需要将其转换为 boolean 值。目前它总是将其转换为 True
,即使该值设置为 False
。
这是我正在尝试做的 MWE
:
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
。这种安排看起来非常复杂,因为这是来自更大代码的最小示例,这就是我将参数读入其中的方式。
为什么flag
总是转换成True
?
最佳答案
bool('True')
和 bool('False')
总是返回 True
因为字符串 'True' 和 'False' 是不为空。
引用一位伟人(和 Python documentation ):
5.1. Truth Value Testing
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:
- …
- zero of any numeric type, for example,
0
,0L
,0.0
,0j
.- any empty sequence, for example,
''
,()
,[]
.- …
All other values are considered true — so objects of many types are always true.
内置bool
函数使用标准的真值测试程序。这就是为什么你总是得到 True
。
要将字符串转换为 boolean 值,您需要执行以下操作:
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
关于python - 将从文件读取的 True/False 值转换为 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21732123/