布爾("字符串"),但總是得到真
實際上,你只需將字符串與期望接受的內容進行比較,這樣你就可以這樣做: s == 'True' 或者檢查一組值: 復制代碼 s in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh'] 使用以下命令時要小心: 復制代碼 >>> bool("foo") True >>> bool("") False 空字符串計算為 False,但其他所有內容都計算為 True 。 所以這不應該用於任何解析目的。 原作者: Mike 復制代碼 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 顯式地處理true和 false: 你也可以讓你的函數顯式檢查單詞列表和單詞列表。 如果它在兩個列表中,你可以拋出一個異常。 原作者: Brian R. Bondy 從 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' 我通常不會推薦這個,但是它完全是內置的,根據你的需求,它是正確的。 原作者: 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 類型也很有用。 復制代碼 >>> import json >>> json.loads("false") False >>> json.loads("true") 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 >>> 一個 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值並讓它引發異常( 或者返回無) 當一個值沒有找到,或者默認為真,或者默認為 False,或者任何你想要的。 原作者: Nate 我不贊同任何解決方案,因為它們太寬容了。 在分析字符串時,這通常不是你想要的。 下面是我使用的解決方案: 復制代碼 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 因為我的回答似乎冒犯了某人: 要點是你不想只測試一個值並假設另一個值。 我不認為你總是想把所有的東西映射到非解析的值。 產生容易出錯的代碼。 所以,如果你知道你想要什么代碼。 原作者: estani 你可以簡單地使用內置函數 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'> 這個版本保持了像 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