I am trying to check each index in an 8 digit binary string. If it is '0'
then it is 'OFF'
otherwise it is 'ON'
.
Is there a more concise way to write this code with a switch-like feature?
Pattern matching is the switch-case equivalent in Python 3.10 and newer. A pattern matching statement starts with the match keyword, and it contains one or more case blocks.
Unlike any other programming language, python language does not have switch statement functionality.
Python doesn't have a switch/case statement because of Unsatisfactory Proposals . Nobody has been able to suggest an implementation that works well with Python's syntax and established coding style.
From version 3.10 upwards, Python has implemented a switch case feature called “structural pattern matching”. You can implement this feature with the match and case keywords.
No, it doesn't. When it comes to the language itself, one of the core Python principles 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 as a compiler optimization for C. Modern compilers no longer need these hints to optimize this sort of logic statement.
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]
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