从转换文件读取真/假值布尔 [英] Convert True/False value read from file to boolean

查看:115
本文介绍了从转换文件读取真/假值布尔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读真 - 假从文件中值,我需要将其转换为Boolean。目前,它总是将其转换为即使该值设置为

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 文件基本上是由一个字符串值假里面写的。该装置看起来非常令人费解,因为这是从一个更大的code最小的例子,这是我读的参数进去。

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.

为什么标志总是转换为

推荐答案

布尔('真正')布尔(假)总是返回,因为字符串'真'和'假'是不是空的。

bool('True') and bool('False') always return True because strings 'True' and 'False' are not empty.

要引用AA伟大的人(和Python 文档):

To quote a a great man (and Python documentation):

任何对象都可以为真值进行测试,使用if或同时
  条件或如下布尔运算的操作数。该
  以下值被认为是假的:

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:


      
  • &hellip;

  •   
  • 任何数值类型的零,例如, 0 0L 0.0 0J

  •   
  • 的空序列,例如() []

  •   
  • &hellip;

  •   
  • zero of any numeric type, for example, 0, 0L, 0.0, 0j.
  • any empty sequence, for example, '', (), [].

所有其他值都认为是真&MDASH;许多类型的这样的对象
  总是为真。

All other values are considered true — so objects of many types are always 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

这篇关于从转换文件读取真/假值布尔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆