`
# 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}"')
`
问题:
我的目标是S,W返回(1,S)和(1,W) 但是获得 (None, S) 和 (None, W) 也可以。
有没有办法使用 python unpack 功能来做到这一点?
input: 4S:
. "4", "S"
input: 3W:
. "3", "W"
input: S:
Traceback (most recent call last):
File "C:\Users\karun\Documents\PycharmProjects\test.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)
这样的事情有用吗:
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)