如何在Python中将字符串转换为布尔值?这个尝试返回True:
>>> bool("False")
True
如何在Python中将字符串转换为布尔值?这个尝试返回True:
>>> bool("False")
True
当前回答
在python 3.10版本中,你可以这样做;
def stringToBool(string: str) -> bool:
match(string.lower()):
case 'true':
return True
case 'false':
return False
match-statement等价于c++中的switch。
其他回答
警告:此答案从Python 3.12起不再有效(从3.10起已弃用)
Use:
bool(distutils.util.strtobool(some_string))
Python 2: http://docs.python.org/2/distutils/apiref.html?highlight=distutils.util#distutils.util.strtobool Python >=3, <3.12: https://docs.python.org/3/distutils/apiref.html#distutils.util.strtobool Python >=3.12:由于PEP 632,不再是标准库的一部分
真值是y, yes, t, True, on和1;假值为n, no, f, False, off和0。如果val为其他值,则引发ValueError。
请注意,distutils.util. strtoool()返回整数表示,因此需要用bool()包装它以获得布尔值。
鉴于distutils将不再是标准库的一部分,下面是distutils.util. strtoool()的代码(请参阅源代码)。
def strtobool (val):
"""Convert a string representation of truth to true (1) or false (0).
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else.
"""
val = val.lower()
if val in ('y', 'yes', 't', 'true', 'on', '1'):
return 1
elif val in ('n', 'no', 'f', 'false', 'off', '0'):
return 0
else:
raise ValueError("invalid truth value %r" % (val,))
这里有一个复杂的,内置的方法来得到许多相同的答案。请注意,尽管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实例,这是相对繁重的。
什么是true或false取决于Tcl_GetBoolean的行为,它将0、false、no和off视为false,将1、true、yes和on视为true,不区分大小写。任何其他字符串,包括空字符串,都会导致异常。
这是我的版本。它同时检查正值和负值列表,对于未知值引发异常。它不接收字符串,但任何类型都可以。
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
>>>
我不同意任何解决办法,因为他们太宽容了。在解析字符串时,这通常不是您想要的结果。
这里是我使用的解决方案:
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
澄清一下,因为我的回答似乎冒犯了某人:
关键在于,您不希望只测试一个值,并假设另一个值。我不认为你总是想把所有东西都映射到未解析的值。这会产生容易出错的代码。
如果你知道你想要什么,就把它编码进去。
你可以这样做
my_string = "false"
val = (my_string == "true")
parens中的位将计算为False。这是另一种不需要进行实际函数调用的方法。