首页 文章

在Python中从字符串转换为布尔值?

提问于
浏览
514

有没有人知道如何在Python中从字符串转换为布尔值?我找到this link . 但它看起来不像是一种正确的方法 . 即使用内置功能等

编辑:

我问这个的原因是因为我从这里学到了 int("string") . 我试过 bool("string") 但总是得到 True .

>>> bool("False")
True

26 回答

  • 0

    实际上,您只需将字符串与您希望接受的任何字符串进行比较即可,因此您可以这样做:

    s == 'True'
    

    或者检查一大堆值:

    s in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh']
    

    使用以下内容时要小心:

    >>> bool("foo")
    True
    >>> bool("")
    False
    

    空字符串计算为 False ,但其他所有内容的计算结果为 True . 所以这不应该用于任何类型的解析目的 .

  • 7
    def str2bool(v):
      return v.lower() in ("yes", "true", "t", "1")
    

    然后像这样调用它:

    str2bool("yes")
    

    > True

    str2bool("no")
    

    > False

    str2bool("stuff")
    

    > False

    str2bool("1")
    

    > True

    str2bool("0")
    

    > False


    Handling true and false explicitly:

    您还可以使您的函数显式检查True列表和错误的单词列表 . 然后,如果它不在两个列表中,您可以抛出异常 .

  • 6

    只需使用:

    distutils.util.strtobool(some_string)
    

    http://docs.python.org/2/distutils/apiref.html?highlight=distutils.util#distutils.util.strtobool

    真值是y,yes,t,true,on和1; false值为n,no,f,false,off和0.如果val为其他值,则引发ValueError .

  • 0

    还有另一种选择

    from ansible.module_utils.parsing.convert_bool import boolean
    boolean('no')
    # False
    boolean('yEs')
    # True
    boolean('true')
    # True
    

    但是在 生产环境 中如果你不需要ansible及其所有依赖项,那么好主意就是查看它的代码并复制你需要的逻辑部分:https://github.com/ansible/ansible/blob/2bd6b1415b9131c3a7cb13724f5d31bb0d33846b/lib/ansible/module_utils/parsing/convert_bool.py

  • 5

    从Python 2.6开始,现在有 ast.literal_eval

    >>> import ast
    >>> help(ast.literal_eval)
    Help on function literal_eval in module ast:
    
    literal_eval(node_or_string)
        Safely evaluate an expression node or a string containing a Python
        expression.  The string or node provided may only consist of the following
        Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
        and None.
    

    这似乎有效,只要你是 sure 你的字符串将是 "True""False"

    >>> ast.literal_eval("True")
    True
    >>> ast.literal_eval("False")
    False
    >>> ast.literal_eval("F")
    Traceback (most recent call last):
      File "", line 1, in 
      File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 68, in literal_eval
        return _convert(node_or_string)
      File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 67, in _convert
        raise ValueError('malformed string')
    ValueError: malformed string
    >>> ast.literal_eval("'False'")
    'False'
    

    我通常不会推荐这个,但它完全是内置的,根据您的要求可能是正确的 .

  • 3

    JSON解析器通常也可用于将字符串转换为合理的python类型 .

    >>> import json
    >>> json.loads("false".lower())
    False
    >>> json.loads("True".lower())
    True
    
  • 0

    此版本保留构造函数的语义,如int(value),并提供了一种定义可接受的字符串值的简便方法 .

    def to_bool(value):
        valid = {'true': True, 't': True, '1': True,
                 'false': False, 'f': False, '0': False,
                 }   
    
        if isinstance(value, bool):
            return value
    
        if not isinstance(value, basestring):
            raise ValueError('invalid literal for boolean. Not a string.')
    
        lower_value = value.lower()
        if lower_value in valid:
            return valid[lower_value]
        else:
            raise ValueError('invalid literal for boolean: "%s"' % value)
    
    
    # Test cases
    assert to_bool('true'), '"true" is True' 
    assert to_bool('True'), '"True" is True' 
    assert to_bool('TRue'), '"TRue" is True' 
    assert to_bool('TRUE'), '"TRUE" is True' 
    assert to_bool('T'), '"T" is True' 
    assert to_bool('t'), '"t" is True' 
    assert to_bool('1'), '"1" is True' 
    assert to_bool(True), 'True is True' 
    assert to_bool(u'true'), 'unicode "true" is True'
    
    assert to_bool('false') is False, '"false" is False' 
    assert to_bool('False') is False, '"False" is False' 
    assert to_bool('FAlse') is False, '"FAlse" is False' 
    assert to_bool('FALSE') is False, '"FALSE" is False' 
    assert to_bool('F') is False, '"F" is False' 
    assert to_bool('f') is False, '"f" is False' 
    assert to_bool('0') is False, '"0" is False' 
    assert to_bool(False) is False, 'False is False'
    assert to_bool(u'false') is False, 'unicode "false" is False'
    
    # Expect ValueError to be raised for invalid parameter...
    try:
        to_bool('')
        to_bool(12)
        to_bool([])
        to_bool('yes')
        to_bool('FOObar')
    except ValueError, e:
        pass
    
  • 3

    这是我的版本 . 它会检查正值和负值列表,从而引发未知值的异常 . 并且它没有收到字符串,但任何类型都应该这样做 .

    def to_bool(value):
        """
           Converts 'something' to boolean. Raises exception for invalid formats
               Possible True  values: 1, True, "1", "TRue", "yes", "y", "t"
               Possible False values: 0, False, None, [], {}, "", "0", "faLse", "no", "n", "f", 0.0, ...
        """
        if str(value).lower() in ("yes", "y", "true",  "t", "1"): return True
        if str(value).lower() in ("no",  "n", "false", "f", "0", "0.0", "", "none", "[]", "{}"): return False
        raise Exception('Invalid value for boolean conversion: ' + str(value))
    

    样品运行:

    >>> to_bool(True)
    True
    >>> to_bool("tRUe")
    True
    >>> to_bool("1")
    True
    >>> to_bool(1)
    True
    >>> to_bool(2)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 9, in to_bool
    Exception: Invalid value for boolean conversion: 2
    >>> to_bool([])
    False
    >>> to_bool({})
    False
    >>> to_bool(None)
    False
    >>> to_bool("Wasssaaaaa")
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 9, in to_bool
    Exception: Invalid value for boolean conversion: Wasssaaaaa
    >>>
    
  • 14

    你总能做点什么

    myString = "false"
    val = (myString == "true")
    

    parens中的位将评估为False . 这是另一种方法,无需进行实际的函数调用 .

  • 73

    您只需使用内置函数eval()

    a='True'
    if a is True:
        print 'a is True, a type is', type(a)
    else:
        print "a isn't True, a type is", type(a)
    b = eval(a)
    if b is True:
        print 'b is True, b type is', type(b)
    else:
        print "b isn't True, b type is", type(b)
    

    和输出:

    a isn't True, a type is <type 'str'>
    b is True, b type is <type 'bool'>
    
  • 8

    我不同意这里的任何解决方案,因为它们太宽容了 . 在解析字符串时,这通常不是您想要的 .

    所以我在这里使用的解决方案:

    def to_bool(bool_str):
        """Parse the string and return the boolean value encoded or raise an exception"""
        if isinstance(bool_str, basestring) and bool_str: 
            if bool_str.lower() in ['true', 't', '1']: return True
            elif bool_str.lower() in ['false', 'f', '0']: return False
    
        #if here we couldn't parse it
        raise ValueError("%s is no recognized as a boolean value" % bool_str)
    

    结果如下:

    >>> [to_bool(v) for v in ['true','t','1','F','FALSE','0']]
    [True, True, True, False, False, False]
    >>> to_bool("")
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 8, in to_bool
    ValueError: '' is no recognized as a boolean value
    

    只是要清楚,因为看起来好像我的答案以某种方式冒犯了某人:

    关键是你不想只测试一个值并假设另一个值 . 我不认为你总是想把所有的东西都映射到非解析的值 . 这会产生容易出错的代码 .

    所以,如果你知道你想要什么代码 .

  • 1

    一个很酷的简单技巧(基于@Alan Marchiori发布的内容),但是使用了yaml:

    import yaml
    
    parsed = yaml.load("true")
    print bool(parsed)
    

    如果这个太宽,可以通过测试类型结果来改进它 . 如果yaml返回的类型是str,那么它不能被转换为任何其他类型(我能想到的任何类型),所以你可以单独处理它,或者只是让它成为真 .

    我不会在速度上做任何猜测,但是因为我正在使用Qt gui下的yaml数据,所以它具有很好的对称性 .

  • 2

    你可能已经有了一个解决方案,但是对于那些正在寻找一种方法来使用“标准”错误值将值转换为布尔值的方法,包括None,[],{}和“”以及false,no和0 .

    def toBoolean( val ):
        """ 
        Get the boolean value of the provided input.
    
            If the value is a boolean return the value.
            Otherwise check to see if the value is in 
            ["false", "f", "no", "n", "none", "0", "[]", "{}", "" ]
            and returns True if value is not in the list
        """
    
        if val is True or val is False:
            return val
    
        falseItems = ["false", "f", "no", "n", "none", "0", "[]", "{}", "" ]
    
        return not str( val ).strip().lower() in falseItems
    
  • 213

    dict(真的,一个defaultdict)为你提供了一个非常简单的方法来实现这个技巧:

    from collections import defaultdict
    bool_mapping = defaultdict(bool) # Will give you False for non-found values
    for val in ['True', 'yes', ...]:
        bool_mapping[val] = True
    
    print(bool_mapping['True']) # True
    print(bool_mapping['kitten']) # False
    

    将这个方法定制为你想要的确切转换行为真的很容易 - 你可以用允许的Truthy和Falsy值填充它,并在找不到值时引发异常(或返回None),或者默认为True,或默认为False,或任何你想要的 .

  • 3

    这是我写的版本 . 将其他几种解决方案合二为一 .

    def to_bool(value):
        """
        Converts 'something' to boolean. Raises exception if it gets a string it doesn't handle.
        Case is ignored for strings. These string values are handled:
          True: 'True', "1", "TRue", "yes", "y", "t"
          False: "", "0", "faLse", "no", "n", "f"
        Non-string values are passed to bool.
        """
        if type(value) == type(''):
            if value.lower() in ("yes", "y", "true",  "t", "1"):
                return True
            if value.lower() in ("no",  "n", "false", "f", "0", ""):
                return False
            raise Exception('Invalid value for boolean conversion: ' + value)
        return bool(value)
    

    如果它获得一个字符串,它需要特定的值,否则会引发异常 . 如果它没有得到一个字符串,只需让bool构造函数弄清楚它 . 测试了这些情况:

    test_cases = [
        ('true', True),
        ('t', True),
        ('yes', True),
        ('y', True),
        ('1', True),
        ('false', False),
        ('f', False),
        ('no', False),
        ('n', False),
        ('0', False),
        ('', False),
        (1, True),
        (0, False),
        (1.0, True),
        (0.0, False),
        ([], False),
        ({}, False),
        ((), False),
        ([1], True),
        ({1:2}, True),
        ((1,), True),
        (None, False),
        (object(), True),
        ]
    
  • 0

    我喜欢使用三元运算符,因为对于感觉它不应超过1行的东西,它更简洁一些 .

    True if myString=="True" else False
    
  • 9

    投射到布尔的通常规则是一些特殊的文字( False00.0()[]{} )是假的,然后其他一切都是真的,所以我建议如下:

    def boolify(val):
        if (isinstance(val, basestring) and bool(val)):
            return not val in ('False', '0', '0.0')
        else:
            return bool(val)
    
  • 5

    我意识到这是一个旧帖子,但有些解决方案需要相当多的代码,这就是我最终使用的内容:

    def str2bool(value):
        return {"True": True, "true": True}.get(value, False)
    
  • 3

    如果您知道字符串将是 "True""False" ,则可以使用 eval(s) .

    >>> eval("True")
    True
    >>> eval("False")
    False
    

    只有你确定字符串的内容时才使用它,因为它会抛出一个如果字符串不包含有效的Python,则异常,并且还将执行字符串中包含的代码 .

  • -4

    如果您知道您的输入将是“True”或“False”,那么为什么不使用:

    def bool_convert(s):
        return s == "True"
    
  • 97

    这是一个毛茸茸的,内置的方式来获得许多相同的答案 . 请注意,虽然python认为 "" 是假的而其他所有字符串都是真的,但TCL对事物的看法却截然不同 .

    >>> import Tkinter
    >>> tk = Tkinter.Tk()
    >>> var = Tkinter.BooleanVar(tk)
    >>> var.set("false")
    >>> var.get()
    False
    >>> var.set("1")
    >>> var.get()
    True
    >>> var.set("[exec 'rm -r /']")
    >>> var.get()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/usr/lib/python2.5/lib-tk/Tkinter.py", line 324, in get
        return self._tk.getboolean(self._tk.globalgetvar(self._name))
    _tkinter.TclError: 0expected boolean value but got "[exec 'rm -r /']"
    >>>
    

    关于这一点的一个好处是它对你可以使用的值非常宽容 . 关于将字符串转换为值是懒惰的,它是关于它接受和拒绝的内容(请注意,如果上面的语句是在tcl提示符处给出的话,它会擦除用户的硬盘) .

    坏的是它需要Tkinter可用,这通常是,但不是普遍真实的,更重要的是,需要创建一个相对较重的Tk实例 .

    什么被认为是真或假取决于 Tcl_GetBoolean 的行为,它认为 0falsenooff 为假, 1trueyeson 为真,不区分大小写 . 任何其他字符串(包括空字符串)都会导致异常 .

  • 3
    def str2bool(str):
      if isinstance(str, basestring) and str.lower() in ['0','false','no']:
        return False
      else:
        return bool(str)
    

    想法:检查是否要将字符串计算为False;否则bool()为任何非空字符串返回True .

  • 612

    这是我一起评估字符串真实性的东西:

    def as_bool(val):
     if val:
      try:
       if not int(val): val=False
      except: pass
      try:
       if val.lower()=="false": val=False
      except: pass
     return bool(val)
    

    与使用 eval 或多或少相同的结果,但更安全 .

  • 12

    我只是不得不这样做...所以也许迟到了 - 但有人可能觉得它很有用

    def str_to_bool(input, default):
        """
        | Default | not_default_str | input   | result
        | T       |  "false"        | "true"  |  T
        | T       |  "false"        | "false" |  F
        | F       |  "true"         | "true"  |  T
        | F       |  "true"         | "false" |  F
    
        """
        if default:
            not_default_str = "false"
        else:
            not_default_str = "true"
    
        if input.lower() == not_default_str:
            return not default
        else:
            return default
    
  • 0

    如果您可以控制返回 true / false 的实体,则一个选项是让它返回 1 / 0 而不是 true / false ,然后:

    boolean_response = bool(int(response))

    int 的额外强制转换处理来自网络的响应,这些响应始终是字符串 .

  • 187

    通过使用Python的内置 eval() 函数和 .capitalize() 方法,您可以将任何"true" / "false"字符串(无论初始大小写)转换为真正的Python布尔值 .

    例如:

    true_false = "trUE"
    type(true_false)
    
    # OUTPUT: <type 'str'>
    
    true_false = eval(true_false.capitalize())
    type(true_false)
    
    # OUTPUT: <type 'bool'>
    

相关问题