Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I tell Python to convert integers into words

Tags:

python

I'm trying to tell Python to convert integers into words.

Example: (using the song 99 bottles of beer on the wall)

I used this code to write the program:

for i in range(99,0,-1):     print i, "Bottles of beer on the wall,"     print i, "bottles of beer."     print "Take one down and pass it around,"     print i-1, "bottles of beer on the wall."     print 

But I cannot figure out how to write the program so that the words (i.e. Ninety nine, Ninety eight, etc.) will be displayed instead of the numbers.

I have been wracking my head in the python book I have, I understand that maybe I just do not understand for/if/elif/else loops yet but I'm just spinning my wheels.

Could anyone provide any insight? I'm not looking for a direct answer, although that might help me see my problem, just anything to point me in the right direction would be great.

like image 951
Lgmccracken Avatar asked Jan 24 '12 04:01

Lgmccracken


People also ask

Which command converts a number to a string Python?

The str() function can be used to change any numeric type to a string.


1 Answers

The inflect package can do this.

https://pypi.python.org/pypi/inflect

$ pip install inflect 

and then:

>>>import inflect >>>p = inflect.engine() >>>p.number_to_words(99) ninety-nine 
like image 71
Lee Avatar answered Oct 04 '22 16:10

Lee