user3579594
user3579594

Reputation:

How to convert Strings to into a phone number

I've been stuck on this questions for so long this is the question:

Write a function that takes a string as an argument and returns the phone number corresponding to that string as the result. The phone number should also be a string. The conversion rules are the standard word to phone number rules:

'a', 'b' or 'c' maps to 2

'd', 'e' or 'f' maps to 3

'g', 'h' or 'i' maps to 4

'j', 'k', or 'l' maps to 5

'm', 'n', or 'o' maps to 6

'p', 'q', 'r', or 's' maps to 7

't', 'u', or 'v' maps to 8

'w', 'x', 'y', or 'z' maps to 9.

Basically I tried

for char in word:
    if char == 'a' or char == 'b' or char == 'c':
    print 2,

and so on but when I call the function strng_to_num("apples") the output is 2 7 7 5 3 7 where I want '277537'. Is there anyway to remove the spaces?

Upvotes: 3

Views: 3093

Answers (3)

savanto
savanto

Reputation: 4550

Don't print each number individually. Instead, add them to a list, and print them all together at the end:

phone_num = []
for char in word:
    if char == 'a' or char == 'b' or char == 'c':
       phone_num.append('2')
    elif char == 'd' or char == 'e' or char == 'f':
       phone_num.append('3')
    ...
print ''.join(phone_num)

You can make your if statements a little simpler by writing:

if char in 'abc':
    ...
elif char in 'def':
    ...

Upvotes: 3

Adam Smith
Adam Smith

Reputation: 54223

I'd do it like this:

def string_to_num(in_str):
    try:
        translationdict = str.maketrans("abcdefghijklmnopqrstuvwxyz","22233344455566677778889999")
    except AttributeError:
        import string
        translationdict = string.maketrans("abcdefghijklmnopqrstuvwxyz","22233344455566677778889999")

    out_str = in_str.lower().translate(translationdict)
    return out_str

The algorithm ooga alluded to in the comment to the question is definitely faster but requires a bit more intense thought than just building a translation dict. This way works for python2 or python3, but here are the relevant docs for maketrans in Python2 and Python3

Upvotes: 10

John B
John B

Reputation: 3646

You could create a dictionary and iterate through each character, then compare to each dictionary key.

def phone(arg):
    num_dict = {'abc': "2",
               'def': "3",
               'ghi': "4",
               'jkl': "5",
               'mno': "6",
               'pqrs': "7",
               'tuv': "8",
               'wxyz': "9" }
    string = ""
    for c in arg:
            for k in num_dict.keys():
                    if c in k:
                            string += num_dict[k]
    return string

Upvotes: 0

Related Questions