Is there a way to convert true
of type unicode
to 1 and false
of type unicode
to 0 (in Python)?
For example: x
If you need a general purpose conversion from a string which per se is not a bool, you should better write a routine similar to the one depicted below. In keeping with the spirit of duck typing, I have not silently passed the error but converted it as appropriate for the current scenario.
>>> def str2bool(st):
try:
return ['false', 'true'].index(st.lower())
except (ValueError, AttributeError):
raise ValueError('no Valid Conversion Possible')
>>> str2bool('garbaze')
Traceback (most recent call last):
File "", line 1, in
str2bool('garbaze')
File "", line 5, in str2bool
raise TypeError('no Valid COnversion Possible')
TypeError: no Valid Conversion Possible
>>> str2bool('false')
0
>>> str2bool('True')
1