Converting Integers to Words in Python
Transforming numerical values into their corresponding word representations can be a perplexing task in Python. This article explores a straightforward solution using the inflect package.
The Dilemma:
The example provided attempts to print the lyrics of the song "99 Bottles of Beer on the Wall" by replacing the numerical values with words. However, the code currently displays the numbers instead of their verbal counterparts.
The Solution:
Fortunately, the inflect package provides a simple way to convert integers to words in Python. Follow these steps:
$ pip install inflect
import inflect
p = inflect.engine()
p.number_to_words(99)
Output:
ninety-nine
Example:
Rewriting the provided example using inflect:
import inflect
p = inflect.engine()
for i in range(99, 0, -1):
print(p.number_to_words(i), "Bottles of beer on the wall,")
print(p.number_to_words(i), "bottles of beer.")
print("Take one down and pass it around,")
print(p.number_to_words(i - 1), "bottles of beer on the wall.")
print()
This code will now print the lyrics of "99 Bottles of Beer on the Wall" using words instead of numbers.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3