在python中将字母数字字符串转换为数字字符串

时间:2017-08-23 13:14:47

标签: python string alphanumeric

我有一个字母数字作为字符串“4525ABT2”,我试图“翻译”成只是一个数字。我尝试了很多方法,非常愚蠢和冗长,并且全神贯注(我在这里找到了Java的解决方案,但它在python中不起作用。也没有将所有字符都改为数字的解决方案)。 我的最后一次尝试看起来像这样

for i in alpha:    
        alpha1 = alpha.replace("A" or "B" or "C", "2")
        alpha2 = alpha1.replace("D" or "E" or "F", "3")
        alpha3 = alpha2.replace("G" or "H" or "I", "4")
        alpha4 = alpha3.replace("J" or "K" or "L", "5")
        alpha5 = alpha4.replace("M" or "N" or "O", "6")
        alpha6 = alpha5.replace("P" or "Q" or "R" or "S", "7")
        alpha7 = alpha6.replace("T" or "U" or "V", "8")
        alpha8 = alpha7.replace("W" or "X" or "Y" or "Z", "9")

phone = str(alpha8)
return phone

提前致谢!!

2 个答案:

答案 0 :(得分:5)

使用合适的工具:

>>> s = "4525ABT2"
>>> table = str.maketrans('ABCDEFGHIJKLMNOPQRSTUVWXYZ',
                          '22233344455566677778889999')
>>> s.translate(table)
'45252282'

答案 1 :(得分:-1)

如果您的替换件尺寸相同会更容易,但这应该有效:

replist = ["","","ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"]

for i,v in enumerate(replist):
    for l in v:
        alpha = alpha.replace(l,str(i))

输入:“AHK62ZT”

输出:“2456298”