Reputation: 31
I've got an alphanumeric number as a string "4525ABT2", which I'm trying to "translate" to be only a numeric one. I tried many ways, smart as really stupid and long, and looked all over (I found the solution for Java here but it doesn't work in python. Neither does the solution that change all characters to numbers). My last attempt looks like this
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
Thanks in advance!!
Upvotes: 3
Views: 1976
Reputation: 446
It would be easier if your replacements were the same size, but this should work:
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))
Input: "AHK62ZT"
Output: "2456298"
Upvotes: -1
Reputation:
Use the proper tool:
>>> s = "4525ABT2"
>>> table = str.maketrans('ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'22233344455566677778889999')
>>> s.translate(table)
'45252282'
Upvotes: 5