How to convert number to words

I’m beginner, i have homework that requires the user to input a number and it convert it to words.For example:

15342

to

one five three four two

this’s my code, but it only work with a number:

def convert_text():
    arr = ['zero','one','two','three','four','five','six','seven','eight','nine']   
    word = arr[n]
    return word
n =int(input())
print(convert_text())

I am not allowed to use the num2word library and dictionary.

>Solution :

Keep the value you pas being a string, then you can iterate over its chars

arr = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']

def convert_text(value):
    result = []
    for char in value:
        result.append(arr[int(char)])
    return " ".join(result)

print(convert_text("1625"))  # one six two five
print(convert_text("98322"))  # nine eight three two two

n = input()
print(convert_text(n))

Or just with generator syntax

def convert_text(value):
    return " ".join(arr[int(char)] for char in value)

Leave a Reply