I have a unicode variable called uploaded. It is a unicode and is retrieved from web request. it's value is either u'Trueor u'False. I need to check it's value to see if it's true or false but if uploaded: always evaluates to True. What's the best way of checking this in python?
Asked
Active
Viewed 3,502 times
3
Nicky Mirfallah
- 1,004
- 4
- 16
- 38
-
6What about `if uploaded == u"True"`? – May 12 '16 at 14:02
-
This answer might be helpful: http://stackoverflow.com/questions/21732123/convert-true-false-value-read-from-file-to-boolean – jano May 12 '16 at 14:05
1 Answers
8
You have a string value, you'll need to see if the literal text 'True' is contained in that string:
if uploaded == u'True':
Any non-empty string object is considered true in a truth test, so the string u'False' is true too!
Alternatively, you could use the ast.literal_eval() function to interpret the string contents as a Python literal; this would also support other types:
import ast
if ast.literal_eval(uploaded):
ast.literal_eval(u'True') would return the actual boolean True object, ast.literal_eval(u'False') would give you the actual False value.
Martijn Pieters
- 1,048,767
- 296
- 4,058
- 3,343