Hey,
I have to do a script for class in which a user inputs a phone number like the ones you see on TV. 555-buy-this I need to make a script that will change the alphabetic characters to numbers. I asked my teacher and he said we had to do it using a list. I am totally lost and would appreciate any help.

Well there are a few ways to do it. Preferably i would use a dictionary but as we cant here is another way:

import string
number = raw_input("Please enter the number:").lower()
n_list = list(number)

for enu,f in enumerate(number):
    if f in string.ascii_lowercase:
        i = string.ascii_lowercase.index(f)+2
        i /= 3
        if i == 0:
            i +=1
       
        
        n_list[enu] = '123456789'[i]
        
print ''.join(n_list)

an example output:

Please enter the number:1800-testing
1800-8378463

Wow.. that worked better then i thought it would.
Enjoy!

Not to be picky, but string method isalpha() is preferable by some. This will avoid the string module:

def phone_alpha_number(phone_num):
    nums = '22233344455566677778889999'
    alphas = 'abcdefghijklmnopqrstuvwxyz'
    return ''.join([[s, nums[alphas.find(s)]][s.isalpha() or 0] for s in phone_num])

Example:

>>> phone_alpha_number('(555)not-best')
'(555)668-2378'
>>>

I know it's a ridiculous use of a list comprehension, but I would not expect the OP to turn this in for his homework.

As has already been hinted, you are probably expected to use 2 lists. The first contains letters and the second contains the number for the corresponding letter. You could also use a list of lists, with each sub-list containing the letter and number, but that is probably more than you can wrap your head around at this point. Do whatever makes sense to you. There are only 26 letters in the English alphabet, so the list is very small, which means that any method with take about the same amount of time. Code something, and append it to the thread for additional help.

paulthom12345 --I tried your way and I couldn't get it to work. Some of the letters could turn to numbers but now all of them. I don't know why it would change some letters and not all of them.

The suggestion about using a dictionary is a good one, I had not thought of it myself. I might try it that way and if the teacher dont like it well, tough luck for him

This article has been dead for over six months. Start a new discussion instead.