# Code
re_freq = re.compile(r'^(?P<num>d+)?(?P<freq>w)')
for input in ['4S', '3W', 'S', 'W']:
print(f'input: {input}:')
num, freq = re_freq.search(input).group()
print(f'. "{num}", "{freq}"')
Issue:
- “4S” and “3W” unpacks successfully because both groups exits: (4, S) and (3, W)
- But “S” and “W” raise ValueError: not enough values to unpack (expected 2, got 1)
My goal is for S, W to return (1, S) and (1, W)
But getting (None, S) and (None, W) would also work.
Is there a way to do this by using python unpack feature?
input: 4S:
. "4", "S"
input: 3W:
. "3", "W"
input: S:
Traceback (most recent call last):
File "C:UserskarunDocumentsPycharmProjectstest.py", line 114, in <module>
num, freq = re.search(r'^(?P<num>d+)?(?P<freq>w)', input).group()
^^^^^^^^^
ValueError: not enough values to unpack (expected 2, got 1)
2
Would something like this work:
for input in ['4S', '3W', 'S', 'W']:
... print(f'input: {input}:')
... if len(input)>1:
... num, freq = re_freq.search(input).group()
... print(f'. "{num}", "{freq}"')
... else:
... print(1, input)
1