Search code examples
pythonstringbooleanreturn-valuetransformation

How can I convert String to Boolean in python?


I need to get the value True and False from the string "True and False".


Solution

  • You can use the eval function to test the condition and then the str function to go back:

    >>> condition = 'True and False'
    >>> test = eval(condition)
    >>> test
    False
    >>> type(test)
    <class 'bool'>
    >>> result = str(test)
    >>> result
    'False'
    >>> type(result)
    <class 'str'>