【发布时间】:2020-07-14 08:41:41
【问题描述】:
我需要在 Python 或 Shell 脚本中生成 4 个字符的序列号,如下所示。
Serial number should start from 0001, 0002..... when reached 999 it should generate A001,A002....A999, then B001, so on.
我在 Python 中尝试了下面的代码,但它没有完全工作,在几个数字后它开始生成 5 个字符..
def excel_format(num):
res = ""
while num:
mod = (num - 1) % 26
res = chr(65 + mod) + res
num = (num - mod) // 26
return res
def full_format(num, d=3):
set_flag = 0
chars = num // (10**d-1) + 1 # this becomes A..ZZZ
if len(excel_format(chars)) >= 2:
set_flag = 1
if len(excel_format(chars)) > 2:
set_flag = 2
if set_flag == 1:
d = 2
chars = num // (10 ** d - 1) + 1 # this becomes A..ZZZ
digit = num % (10**d-1) + 1 # this becomes 001..999
return excel_format(chars) + "{:0{}d}".format(digit, d)
if __name__ == '__main__':
for i in range(1,10001):
unique_code = full_format(j, d=3)
print('Unique Code is =>', unique_code)
【问题讨论】:
-
我们无法帮助您编写代码,但我们可以帮助您解决您遇到的困难!所以请向我们展示你的努力。
标签: python-2.7 ksh