我不确定是否有更Pythonic的方式来做这件事,但是使用一些正则表达式和 python 的format语法,我们可以相当容易地处理您的输入。这是一个解决方案:
import re
def address_list(address_range):
begin,end = address_range.split('-')
Nb,Ne=re.findall(r"\d+", address_range)
#we deduce the paading from the digits of begin
padding=len(re.findall(r"\d+", begin)[0])
#first we decide whether we should use begin or end as a template for the ouput
#here we keep the first that is matching something like ab01 or 01ab
template_base = re.findall(r"[a-zA-Z]+\d+|\d+[a-zA-Z]+", address_range)[0]
#we make a template by replacing the digits of end by some format syntax
template=template_base.replace(re.findall(r"\d+", template_base)[0],"{{:0{:}}}".format(padding))
#print("template : {} , example : {}".format(template,template.format(1)))
return [template.format(x) for x in range(int(Nb), int(Ne)+1)]
print(address_list('1-12A'))
print(address_list('B01-B12'))
print(address_list('C01-9'))
输出:
['1A', '2A', '3A', '4A', '5A', '6A', '7A', '8A', '9A', '10A', '11A', '12A']
['B01', 'B02', 'B03', 'B04', 'B05', 'B06', 'B07', 'B08', 'B09', 'B10', 'B11', 'B12']
['C01', 'C02', 'C03', 'C04', 'C05', 'C06', 'C07', 'C08', 'C09']