[SOLVED] Converting an integer to a sequence of letters using a function

Issue

I want to create a function that takes an integer (say 234) and returns it as letters (cde).

I have managed to form some code that takes the number and separates it into its numeric components

def toLetter(n):
    x = str(n)
    for elem in x:
        print(elem)
    d = {0 : 'a', 1 : 'b', 2 : 'c', 3 : 'd', 4 : 'e', 5 : 'f', 6 : 'g', 7 : 'h', 8 : 'i', 9 : 'j'}
    for n in x:
        d[n]

toLetter(234)

But I am really struggling with;

  1. how to map the dictionary onto the number and
  2. get it to return it as:
cde 

rather than

c
d
e

Any help would be greatly appreciated. I am new so this may be trivial but I have come here as last resort.

Solution

So, in order to select the elements in the dictionary you have to convert the digits back to integers. Also, to create the final answer I would simply append each letter to a string and print the final string:

def toLetter(n):
    d = {0 : 'a', 1 : 'b', 2 : 'c', 3 : 'd', 4 : 'e', 5 : 'f', 6 : 'g', 7 : 'h', 8 : 'i', 9 : 'j'}
    
    x = str(n)
    result = ''
    
    for elem in x:
        result = result + d[int(elem)]
    
    print(result)

toLetter(234)

Output:

cde

Answered By – JANO

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.