Search code examples
pythonconvertersphone-numberletter

Python 2.7 Convert Letters to Phone Numbers


I am trying to complete a code that converts letters into a phone number sequence. What I need is to make for example JeromeB to 537-6632. Also I need the program to cut off the letter translation after the last possible digit. So for example after 1-800-JeromeB even if I write in 1-800-JeromeBrigham it will not code that. The thing is though I do not understand how to implicate that into my code. I do not know understand to cut off the last letter and put in the dash. What I currently have is this

alph = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p',\
        'q','r','s','t','u','v','w','x','y','z']
num =[2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,7,8,8,8,9,9,9,9]


phone = raw_input('enter phone number ').lower()

s = ""
for index in range(len(phone)):
    if phone[index].isalpha():
        s = s + str(num[alph.index(phone[index])])
    else:
        s = s + phone[index]
print s  

Solution

  • # define a dictionary
    alph_num_dict = {'a': '2', 'b': '2', 'c': '2',\
                     'd': '3', 'e': '3', 'f': '3',\
                     'g': '4', 'h': '4', 'i': '4',\
                     'j': '5', 'k': '5', 'l': '5',\
                     'm': '6', 'n': '6', 'o': '6',\
                     'p': '7', 'q': '7', 'r': '7', 's': '7',\
                     'u': '8', 'w': '9', 'v': '8',\
                     'w': '9', 'x': '9', 'y': '9', 'z': '9'}
    

    updated: Cut off chars which follow 7th char, and insert dash in the 4th place

    # define a generator for converting string and cutting off it
    def alph_to_num(phone):
        for index in range(len(phone)):
            if index >= 7:
                return
    
            if index == 4:
                yield '-'
    
            p = phone[index]
    
            if p in alph_num_dict:
                yield alph_num_dict[p]
            else:
                yield p
    

    updated: Enter "end" for termination

    # get input and join all converted char from generator
    while True:
        phone = raw_input('enter phone number in the format xxxxxxx, or enter "end" for termination ').lower()
    
        if phone == 'end':
            break
    
        print ''.join(list(alph_to_num(phone)))
    

    input: JeromeBrigham

    output: 5376-632