kawalek26
kawalek26

Reputation: 33

Convert alphanumeric phone numbers with letters into numbers

I have an assignment where we have to convert alphanumeric phone numbers into just numbers. For example "555-PLS-HELP" should convert into "555-757-4357". I wrote some of it but it keeps giving me incorrect output.

alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
num = '22233344455566677778889999'

phone_number = str(input("Please enter a phone number: "))

counter = len(phone_number[:4])
total = phone_number[:4]
while counter > 0:
    alpha = phone_number[-counter]
    if alpha.isalpha():
        total += num[alph.index(alpha)]
    else:
        total += alpha
    counter -= 1
print(total)

I keep getting weird output.

For example:

Please enter a phone number: '555-PLS-HELP'

Gives:

555-4357

Upvotes: 1

Views: 1400

Answers (5)

ggorlen
ggorlen

Reputation: 57344

There are a few things to consider in your code:

  1. Changing your first slice to counter = len(phone_number[4:]) produces a working solution: you'd like to iterate for the length of the rest of the number rather than the length of the area code prefix.

  2. A simple for n in phone_number is preferable to taking len() and iterating using a counter variable and indexing from the rear with -counter, which is non-intuitive.

  3. input() returns a str; there's no need for a superfluous cast.

This is a perfect situation for a dictionary data structure, which maps keys to values and is an explicit version of what you're already doing. Use zip to combine your strings into a dictionary.

In the list comprehension, each character is looked up in the keypad dictionary and its corresponding entry is returned. Using the dict.get(key, default) method, any items not present in the dictionary will be default.

alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
num = '22233344455566677778889999'
keypad = dict(zip(alph, num))

phone_number = input("Please enter a phone number: ")

print("".join([keypad.get(x, x) for x in phone_number]))

Try it!

Upvotes: 3

Alex Foglia
Alex Foglia

Reputation: 530

Why you are considering only last 4 characters of an a-priori unknown string? You could search first if phone_number has some alphabetic characters, and if it does, then starting from the first occurrence of such an alphabetic character you can replace it with the correct digit. This works for capital letters:

alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
num = '22233344455566677778889999'

phone_number = raw_input("Please enter a phone number: ")


def fstAlpha(string):
    for i in range(0,len(string)):
        if string[i].isalpha():
            return i
return -1

index = fstAlpha(phone_number);

if index != -1:
    for i in range(index,len(phone_number)):
        if(phone_number[i].isalpha()):
            to_replace = phone_number[i]
            replace_with = num[alph.index(to_replace)]
            phone_number = phone_number.replace(to_replace,replace_with)
print phone_number   

Upvotes: 0

Austin
Austin

Reputation: 26047

You could just iterate through the inputted number, check if it's alphabet and get the corresponding number if so, all in one-line:

alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
num = '22233344455566677778889999'

phone_number = input("Please enter a phone number: ")

print(''.join([num[alph.index(x.upper())] if x.isalpha() else x for x in phone_number]))

Sample run:

Please enter a phone number: 555-PLS-HELP
555-757-4357

If it's an alphabet, this gets the index of the alphabet from alph and use that to look up in the num to get corresponding number. In the else case, just copies the number.

Upvotes: 1

iz_
iz_

Reputation: 16633

Try the following:

alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
num = '22233344455566677778889999'
# converts the above lists into a dict
lookup = dict(zip(alph, num))

phone_number = input("Please enter a phone number: ")

result = ''
for c in phone_number:
    # if needs changing
    if c.isalpha():
        result += lookup[c.upper()]
    # simply append otherwise
    else:
        result += c

print(result)

Result:

Please enter a phone number: 555-PLS-HELP

Output:

555-757-4357

Upvotes: 1

Banghua Zhao
Banghua Zhao

Reputation: 1556

alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
num = '22233344455566677778889999'

phone_number = str(input("Please enter a phone number: "))

counter = len(phone_number)
total = ''
while counter > 0:
    alpha = phone_number[-counter]
    if alpha.isalpha():
        total += num[alph.index(alpha)]
    else:
        total += alpha
    counter -= 1
print(total)

Test:

Please enter a phone number: '555-PLS-HELP'

Output:

555-757-4357

Upvotes: 1

Related Questions