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?
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))
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
eval
is not a good idea in general.
I would use the following:
b = False if x == 'False' else True
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?
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))
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
eval
is not a good idea in general.
I would use the following:
b = False if x == 'False' else True