How to return false from string converted in bool

Question:

I can’t return False in settings.py from docker(.env)

DEBUG = os.environ.get('DEBUG_MODE')
DEBUG_MODE=False

Python return:

x = False
bool(x)
False
print(bool(x))
False
x = 'False'
print(bool(x))
True

How to return False?

Asked By: Ormon Saadanbek

||

Answers:

Any non-empty string is truthy, so bool('False') returns True.

You can use a simple comparison:

print(x == 'True')

or you could use ast.literal_eval() to parse any Python literal.

import ast
print(ast.literal_eval(x))
Answered By: Barmar

Just try:

print(eval('False'))

Take a look at its use in the documentation eval()

Answered By: BATMAN

ANY string is binary encoded in ascii. so the code

x = ' ' ; print(bool(x))    | >>> True   |

as its not zero even if x=” ” | where [ ” ” = whitespace ]

if you want to do as you said :

  • METHOD 1 : [ type(x) == str ]:

    • return BOOLEAN True if x= “anyString” & False if other type
  • METHOD 2 : [ isinstance ( x , str ) ]

    • return BOOLEAN True if true , wrap it with str(Your_test) to get string comparison
  • METHOD 3 : Complimentary Logic

    • initially we give | x=’False’
    • boolean_value = x != ‘False’
    • print(boolean_value) | >>> False
    • double compliment : boolean_value = x == ‘True’
    • print(boolean_value) | >>> False
Answered By: nikhil swami

eval is not a good idea in general.

I would use the following:

b = False if x == 'False' else True
Answered By: FrenchCommando
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.