Home > Net >  How to loop over a sting that defines a Range?
How to loop over a sting that defines a Range?

Time:04-15

This may be fairly simple, but i am not able to figure it out.

I am working on a peice of code where i need to loop over a range defined by the string.

Example:


service_range = 'AX000-AX930'

ouput :

'AX000'
'AX001'
'AX002'
'AX003'
'AX004'
.
.
.
'AX929'
'AX930'

I am trying to generate using the code below:

service_range = re.findall(r'\d ', service_range)
print(service_range)    # ['000', '930']

for i in range(int(service_range[0]), int(service_range[1]   1)):
    print(i)  
    count  = 1

above code works however the output is not quite what iwant. I want to preserve the digits & code ('AX')


0
1
2
3
.
.
.
.
930

CodePudding user response:

You may concatenate the prefix, and padd-left the value, with a nicer regex that gives

import re

service_range = 'AX000-AX930'
prefix1, start, prefix2, end = re.search(r'([A-Z] )(\d )-([A-Z] )(\d )',
                                         service_range).groups()

assert prefix1 == prefix2
for i in range(int(start), int(end)   1):
    print(f"{prefix1}{i:03d}")

CodePudding user response:

theList = []
for i in range(931):
    result = "AX" "{0:03}".format(i)
    theList.append(result)
  • Related