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:



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())

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

Asked By: khôi lê



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:
    return " ".join(result)

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

n = input()

Or just with generator syntax

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

You can use this code hope this can help you

def convert_text(n):
    word = ""
    arr = ['zero','one','two','three','four','five','six','seven','eight','nine'] 
    ''' Convert to string n from input for iterate over each single unit'''
    for value in str(n):
       ''' Convert back unit of string into number '''
       num = int(value);
       ''' Add new word to previous words '''
       word = word + " " + arr[num]
    return word
n = int(input())
Answered By: yermartee
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.