Home > Back-end >  How to convert number to words
How to convert number to words

Time:11-24

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.

CodePudding user response:

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)

CodePudding user response:

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())
print(convert_text(n))
  • Related