【问题标题】:Incrementing an alphanumeric string in Python在 Python 中递增字母数字字符串
【发布时间】:2017-04-30 18:47:47
【问题描述】:

我需要构建一个函数,它获取一个字母数字字符串(0、1、...、8、9、A、B、C、...、Z),加 1 并返回字符串。例如:给定 02H9Z,函数应返回 02HA0。

我在网上找到了几个随机字母数字字符串生成器。他们工作得很好,但不能解决我的问题。然后我开始编写一个函数,它检查 for 循环中的每个字符并将其与 'A'、'B'、... 进行比较 - 但我认为这效率不高。

谁能想到更好的解决方案?

【问题讨论】:

标签: python counter increment alphanumeric


【解决方案1】:

那是base 36。使用内置的int函数,和Numpy的numpy.base_repr

import numpy
s = '02H9Z'
new = int(s, 36) + 1
print(numpy.base_repr(new, 36))

【讨论】:

  • 该死的我差点发这个了。
【解决方案2】:

这是仅使用内置函数的解决方案:

l = '0123456789abcdefghijklmnopqrstuvwxyz'

def increase(s):
    new_s = []
    continue_change = True
    for c in s[::-1].lower():
        if continue_change:
            if c == 'z':
                new_s.insert(0, '0')
            else:
                new_s.insert(0, l[l.index(c) + 1])
                continue_change = False
        else:
            new_s.insert(0, c)

    return ''.join(new_s)

【讨论】:

    猜你喜欢
    • 2014-10-08
    • 1970-01-01
    • 2013-10-09
    • 2022-11-15
    • 2011-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    相关资源
    最近更新 更多