Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most Pythonic way to convert 0 and 1 strings to boolean? [duplicate]

Tags:

python

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?

like image 396
danielsore Avatar asked Oct 27 '25 09:10

danielsore


1 Answers

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.

like image 200
NPE Avatar answered Oct 29 '25 23:10

NPE