Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading