如何在Python中将字符串转换为布尔值?这个尝试返回True:
>>> bool("False")
True
如何在Python中将字符串转换为布尔值?这个尝试返回True:
>>> bool("False")
True
当前回答
你可以这样做
my_string = "false"
val = (my_string == "true")
parens中的位将计算为False。这是另一种不需要进行实际函数调用的方法。
其他回答
JSON解析器在将字符串转换为合理的python类型时也很有用。
>>> import json
>>> json.loads("false".lower())
False
>>> json.loads("True".lower())
True
.blink { color: yellow; animation: blink-animation 0.5s infinite; } @keyframes blink-animation { 25% { background-color: black; color: cyan; } 50% { background-color: black; color: red; } 75% { background-color: black; color: lime; } } <h1 class="blink">WARNING: Do not use the following code unless you actually know what you are doing with it. Please read the attached disclaimers and make sure you trust your inputs as using this on untrusted inputs could destroy your data and/or cost you your job.</h1>
如果你知道字符串将是“True”或“False”,你可以使用eval(s)。
>>> eval("True")
True
>>> eval("False")
False
不过,只有在确定字符串的内容时才使用此方法,因为如果字符串不包含有效的Python,它将抛出异常,并且还将执行字符串中包含的代码。
从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.
这似乎是可行的,只要你确定你的字符串将是“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'
我通常不建议这样做,但它是完全内置的,可以根据您的需求来选择。
这是我的版本。它同时检查正值和负值列表,对于未知值引发异常。它不接收字符串,但任何类型都可以。
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
>>>
您可能已经有了一个解决方案,但对于其他人来说,他们正在寻找一种方法,将值转换为布尔值,使用“标准”假值,包括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