>>> 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 Pythonexpression. The string or node provided may only consist of the followingPython 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, inFile "/opt/Python-2.6.1/lib/python2.6/ast.py", line 68, in literal_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'
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
>>> 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_boolException: 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_boolException: Invalid value for boolean conversion: Wasssaaaaa>>>
from collections import defaultdictbool_mapping = defaultdict(bool) # Will give you False for non-found valuesfor val in ['True', 'yes', ...]:bool_mapping[val] = True
print(bool_mapping['True']) # Trueprint(bool_mapping['kitten']) # False
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 Trueif value.lower() in ("no", "n", "false", "f", "0", ""):return Falseraise Exception('Invalid value for boolean conversion: ' + value)return bool(value)
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 Trueelif bool_str.lower() in ['false', 'f', '0']: return False
#if here we couldn't parse itraise 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_boolValueError: '' is no recognized as a boolean 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 casesassert 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
<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>
If you know the string will be either "True" or "False", you could just use eval(s).
>>> eval('true')Traceback (most recent call last):File "<stdin>", line 1, in <module>File "<string>", line 1, in <module>NameError: name 'true' is not defined
>>> eval('false')Traceback (most recent call last):File "<stdin>", line 1, in <module>File "<string>", line 1, in <module>NameError: name 'false' is not defined
def to_bool(value) -> bool:if value == 'true':return Trueelif value == 'True':return Trueelif value == 'false':return Falseelif value == 'False':return Falseelif value == 0:return Falseelif value == 1:return Trueelse:raise ValueError("Value was not recognized as a valid Boolean.")
In [1]: class MyString:...: def __init__(self, value):...: self.value = value...: def __eq__ (self, obj):...: if hasattr(obj, 'value'):...: return obj.value == self.value...: return False...:
In [2]: v = MyString("True")
In [3]: v == "True"Out[3]: False