在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
- 不要使用
作为变量名;它隐藏了一个内置的Pythonstr
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