I am trying to check each index in an 8 digit binary string. If it is '0' then it is 'OFF' otherwise its 'ON'. I'm wondering if there's a more concise way to write this code with a switch-like feature.
Thanks,
I am trying to check each index in an 8 digit binary string. If it is '0' then it is 'OFF' otherwise its 'ON'. I'm wondering if there's a more concise way to write this code with a switch-like feature.
Thanks,
No it doesn't. In the Python core language, one of the rules is to only have one way to do something. The switch is redundant to:
if x == 1:
pass
elif x == 5:
pass
elif x == 10:
pass
(without the fall-through, of course).
The switch was originally introduced to cut down on the number of angle brackets needed to do do similar if blocks, however, with python there are no brackets anyways.
Try this instead:
def on_function(*args, **kwargs):
# do something
def off_function(*args, **kwargs):
# do something
function_dict = { '0' : off_function, '1' : on_function }
for ch in binary_string:
function_dict[ch]()
Or you could use a list comprehension or generator expression if your functions return values:
result_list = [function_dict[ch]() for ch in binary_string]