3

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!!

Ninsa
  • 31
  • 2
  • Providing a link to the Java solution that you mention would probably help others a lot to understand what exactly you are trying to do. – anothernode Aug 23 '17 at 13:30
  • You're right. I should have thought about it. I cannot find the post longer but next time- will do. – Ninsa Aug 23 '17 at 20:26

2 Answers2

5

Use the proper tool:

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

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"

Zinki
  • 446
  • 4
  • 10
  • 1
    this is still a bad solution because replacing characters in a string (in a loop, no less) is expensive. –  Aug 23 '17 at 13:39
  • @hop oh yeah your solution is much better, I just wanted to provide a version that used the same basic principles as OPs original attempt. – Zinki Aug 23 '17 at 14:01