首页 > 解决方案 > 需要生成序列号

问题描述

我需要在 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.7ksh

解决方案


此 Python 代码将生成所需的 4 字符 (Unique_code) 序列号:

#!/usr/bin/python3
import re

for i in range(1,10000):
    if (i < 1000):
       print ("i =", str(i).zfill(4))
    else:
       m = re.findall(r'(\d)(\d\d\d)', str(i))
       code = 64+int(m[0][0])
       print ("i =",i, "Unique_code =", chr(code) + m[0][1])

输出摘录:

i = 0001
i = 0002
...
i = 0999
i = 1000 Unique_code = A000
i = 1001 Unique_code = A001
i = 1002 Unique_code = A002
...
i = 1997 Unique_code = A997
i = 1998 Unique_code = A998
i = 1999 Unique_code = A999
i = 2000 Unique_code = B000
i = 2001 Unique_code = B001
i = 2002 Unique_code = B002
i = 2003 Unique_code = B003
...
i = 9997 Unique_code = I997
i = 9998 Unique_code = I998
i = 9999 Unique_code = I999

推荐阅读