Warm tip: This article is reproduced from serverfault.com, please click

python-将从文件读取的真/假值转换为布尔值

(python - Convert True/False value read from file to boolean)

发布于 2014-02-12 15:26:16

我正在True - False从文件中读取一个值,我需要将其转换为布尔值。目前,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

Questioner
Gabriel
Viewed
22
7,281 2018-04-11 09:18:54

bool('True')并且bool('False')总是返回,True因为字符串 'True' 和 'False' 不为空。

引用一个伟人(和 Python文档):

5.1. 真值测试

任何对象都可以测试真值,用于 if 或 while 条件或作为下面布尔运算的操作数。以下值被认为是错误的:

  • 任何数字类型的零,例如0, 0L, 0.0, 0j
  • 任何空序列,例如,'', (), []

所有其他值都被认为是真——所以许多类型的对象总是真。

内置bool函数使用标准真值测试程序。这就是为什么你总是得到True.

要将字符串转换为布尔值,你需要执行以下操作:

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