python - 将从文件读取的 True/False 值转换为 boolean 值

标签 python string boolean

我正在从文件中读取 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 文件基本上由一个字符串组成,其中写入值 TrueFalse。这种安排看起来非常复杂,因为这是来自更大代码的最小示例,这就是我将参数读入其中的方式。

为什么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/

相关文章:

python - 有没有办法用python将文本输入网站?

python - "ModuleNotFoundError"与使用 Python 的 Azure 函数应用程序

Java:名称列表(String []),我如何/可以使用滚动条显示它们?

c - For 循环不以空终止符终止

c - 将文本文件中的字符串读入结构时出现段错误

MATLAB:快速反转 boolean 值

c - 语句中运算符的优先级和执行

python - 系统在计算上是奇异的 : reciprocal condition number = 1. 59968e-21

python - 我可以在 python 中 "fake"一个包(或至少一个模块)用于测试目的吗?

python - Python .csv 文件中字段的 boolean 值