Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an alphanumeric string into a numeric one in python

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

like image 417
Ninsa Avatar asked Jul 02 '26 17:07

Ninsa


1 Answers

Use the proper tool:

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

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!