Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中将字符串转换为布尔值_Python_String_Boolean - Fatal编程技术网

在Python中将字符串转换为布尔值

在Python中将字符串转换为布尔值,python,string,boolean,Python,String,Boolean,如何将字符串转换为布尔值?例如: str = "False and False or True and True" str = "( "+str+" )" str = str.replace("and",") and (") 返回 str == '( False ) and ( False or True ) and ( True )' 如何对结果“False”执行str?我想您正在寻找: 注释: 不要在用户输入时使用eval,请参见和 不要使用str作为变量名;它隐藏了一个内置的Pyth

如何将字符串转换为布尔值?例如:

str = "False and False or True and True"
str = "( "+str+" )"
str = str.replace("and",") and (")
返回

str == '( False ) and ( False or True ) and ( True )'

如何对结果“False”执行
str

我想您正在寻找:

注释

  • 不要在用户输入时使用
    eval
    ,请参见和
  • 不要使用
    str
    作为变量名;它隐藏了一个内置的Python

您可以使用将适当字符串转换为True和False的函数

def str2bool(self, v): # Note the self to allow it to be in a class
  return v.lower() in ('yes', 'true', 't', '1', 'yea', 'verily')  # lower() is a method

这将允许您分析各种用户输入。

谢谢,jonrsharpe:)这是可行的,但我认为应该有人提及eval的问题:
def str2bool(self, v): # Note the self to allow it to be in a class
  return v.lower() in ('yes', 'true', 't', '1', 'yea', 'verily')  # lower() is a method