实际上,你只需将字符串与期望接受的内容进行比较,这样你就可以这样做:
s== 'True'或者检查一组值:
复制代码
sin ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh']
使用以下命令时要小心:
复制代码>>> bool("foo")
True>>> bool("")
False
空字符串计算为 False,但其他所有内容都计算为 True 。 所以这不应该用于任何解析目的。
原作者: Mike
复制代码defstr2bool(v):return v.lower() in ("yes","true","t","1")
然后像这样调用:
str2bool("yes")>True
str2bool("no")>False
str2bool("stuff")>False
str2bool("1")>True
str2bool("0")>False
显式地处理true和 false:
你也可以让你的函数显式检查单词列表和单词列表。 如果它在两个列表中,你可以抛出一个异常。
原作者: Brian R. Bondy
从 python2.6开始,现在有 ast.literal_eval:
复制代码>>> importast>>>help(ast.literal_eval)
Help on function literal_evalinmodule ast:
literal_eval(node_or_string)
Safely evaluate an expression nodeora string containing a Python
expression. The stringornode provided may only consist of the following
Python literal structures: strings, numbers, tuples, lists, dicts, booleans,andNone.
这似乎很有效,只要你是确保你的字符串是将是要么"True" 或者 "False":
复制代码>>> ast.literal_eval("True")
True>>> ast.literal_eval("False")
False>>> ast.literal_eval("F")
Traceback (most recent call last):
File"", line 1, inFile"/opt/Python-2.6.1/lib/python2.6/ast.py", line 68, inliteral_evalreturn_convert(node_or_string)
File"/opt/Python-2.6.1/lib/python2.6/ast.py", line 67, in_convertraise ValueError('malformed string')
ValueError: malformed string>>> ast.literal_eval("'False'")'False'我通常不会推荐这个,但是它完全是内置的,根据你的需求,它是正确的。
原作者: Jacob Gabrielson
只是使用:
复制代码
distutils.util.strtobool(some_string)
http://docs.python.org/2/distutils/apiref.html?highlight=distutils.util#distutils.util.strtobool
真和1;上的值为y,是的,t,真的,假的值为n,没有,f,false,关闭,0. 如果val是其它的,则抛出 ValueError 。
原作者: schnurstrax
JSON解析器对于将字符串转换为合理的python 类型也很有用。
复制代码>>> importjson>>> json.loads("false")
False>>> json.loads("true")
True
这是我的版本。它对正数和负数都进行检查,引发未知值的异常。 它不接收字符串,但任何类型都应该。
复制代码defto_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"): returnTrueif str(value).lower() in ("no","n","false","f","0","0.0","","none","[]","{}"): returnFalseraise 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"", line 1, in File"", line 9, into_bool
Exception: Invalid valuefor boolean conversion: 2
>>>to_bool([])
False>>>to_bool({})
False>>>to_bool(None)
False>>> to_bool("Wasssaaaaa")
Traceback (most recent call last):
File"", line 1, in File"", line 9, into_bool
Exception: Invalid valueforboolean conversion: Wasssaaaaa>>>一个 dict ( 真的,一个 defaultdict ) 提供了一个非常简单的方法来完成这个技巧:
复制代码from collections importdefaultdict
bool_mapping= defaultdict(bool) #Will give you False for non-found values
for val in ['True', 'yes',.. .]:
bool_mapping[val]=Trueprint(bool_mapping['True']) #True
print(bool_mapping['kitten']) #False
它真的很好到所需的确切转换行为以满足相关方法允许你--可以填补它与Truthy和Falsy值并让它引发异常( 或者返回无) 当一个值没有找到,或者默认为真,或者默认为 False,或者任何你想要的。
原作者: Nate
我不赞同任何解决方案,因为它们太宽容了。 在分析字符串时,这通常不是你想要的。
下面是我使用的解决方案:
复制代码defto_bool(bool_str):"""Parse the string and return the boolean value encoded or raise an exception"""
if isinstance(bool_str, basestring) andbool_str:if bool_str.lower() in ['true', 't', '1']: returnTrueelif bool_str.lower() in ['false', 'f', '0']: returnFalse#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"", line 1, in File"", line 8, into_bool
ValueError:'' isno recognized as a boolean value
因为我的回答似乎冒犯了某人:
要点是你不想只测试一个值并假设另一个值。 我不认为你总是想把所有的东西映射到非解析的值。 产生容易出错的代码。
所以,如果你知道你想要什么代码。
原作者: estani
你可以简单地使用内置函数 eval():
复制代码
a='True'
if a isTrue: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 isTrue: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
b is True, b type is 这个版本保持了像 int(value) 这样的构造函数的语义,提供了一个简单的方法来定义可以接受的字符串值。
复制代码defto_bool(value):
valid= {'true': True, 't': True, '1': True,'false': False, 'f': False, '0': False,
}ifisinstance(value, bool):returnvalueif notisinstance(value, basestring):raise ValueError('invalid literal for boolean. Not a string.')
lower_value=value.lower()if lower_value invalid:returnvalid[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')exceptValueError, e:pass