我需要构建一个函数,它获取一个字母数字字符串(0,1,...,8,9,A,B,C,...,Z),加1并返回字符串。例如:给出02H9Z,该函数应返回02HA0。
我在网上发现了几个随机的字母数字字符串生成器。他们工作得很好,但没有解决我的问题。然后我开始编写一个函数来检查for循环中的每个char,并将它与'A','B',...进行比较 - 但我认为效率不高。
有人能想到更好的解决方案吗?
答案 0 :(得分:3)
那是基础36.使用内置的int
函数和Numpy的numpy.base_repr
:
import numpy
s = '02H9Z'
new = int(s, 36) + 1
print(numpy.base_repr(new, 36))
答案 1 :(得分:0)
以下是仅使用内置函数的解决方案:
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)