I’m reading a value from a General Purpose IO (GPIO) configured as Input and it returns a string that is either 0 or 1. I see two easy ways to convertiing it to boolean:
bool(int(input_value))
or
not not int(input_value)
Which is most Pythonic? Are there more Pythonic ways then the ones presented above?
There are many ways, but I would like to propose the following:
{'0': False, '1': True}[input_value]
This has the advantage of raising an exception if you ever get a value different to what you expect (because of a bug, a malfunction, an API change etc).
All the other options presented thus far will silently accept any string as input.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With