Search code examples
pythonif-statementnumbersreturn

converting phone number into phone 'word' - python


I want to convert given phone number into respective letters

0 -> 'a'
1 -> 'b'
2 -> 'c' etc.

E.g. the number 210344222 should get converted to the string 'cbadeeccc'. I understand my return is wrong at the end which is where I am stuck, so can you please explain how I would instead return the letter conversions.

def phone(x):
    """
    >>> phone(22)
    'cc'
    >>> phone(1403)
    'bead'
    """
    result = "" 
    x = str(x)
    for ch in x: 
        if x == 0:
            print('a')
        elif x == 1:
            print('b')
        elif x == 3:
            print('c')
    return result

Solution

  • You can try utilizing the built-in chr() method:

    def phone(x):
        return ''.join((chr(int(i) + 97)) for i in x)
    
    print(phone('210344222'))
    

    Output:

    cbadeeccc
    

    Where chr(97) returns 'a', chr(98) returns 'b', and so on, hence the int(i) + 97 bit.