2014-02-24 3 views
0

문자열을 부울로 변환하는 방법?파이썬에서 문자열을 부울로 변환

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

반환

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

어떻게 '거짓'결과에 대한 str을 실행하는

: 예를 들면?

답변

2

나는 당신이 eval 찾고있는 생각 :

>>> eval('(False) and (False or True) and (True)') 
False 

: 변수 이름으로 str를 사용하지 않는; 파이썬은 내장되어 있습니다.

+0

감사합니다, jonrsharpe :) – softghost

+0

이것은 작동하지만 누군가가 eval을 사용하여 문제를 언급해야한다고 생각합니다. https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice – leumas95

2

당신은 적절한 문자열을 tranlates 기능을 사용할 수있는 사실이고 이것은 당신이뿐만 아니라 다양한 사용자 입력을 분석 할 수

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 

거짓.

+0

pip 설치 [str2bool] (https://github.com/symonsoft/str2bool) =) – Symon

관련 문제