Have you ever wondered how to convert numbers to words in Python? For example, how to convert 42 into “forty-two” or 2024 into “two thousand and twenty-four”? It can be very useful for various purposes, such as invoices, reading out large numbers, or creating text-based games.
In this blog post, I will show you the best way to convert numbers to words in Python using a popular library called num2words
(https://pypi.org/project/num2words/).
Convert Numbers to Words using num2words
The easiest and fastest way to convert numbers to words in Python is to use the num2words
library. Let's install and use it.
pip install num2words
The num2words
library can convert numbers to words in different languages, formats, and styles. For example, you can convert numbers to ordinal, cardinal, year, or currency forms.
To use the num2words
library, you need to import it and then call the num2words
function with the number as the argument. You can also pass optional keyword arguments to customize the output. Here are some examples:
from num2words import num2words
# Convert a number to cardinal form (default)
print(num2words(42)) # forty-two
# Convert a number to ordinal form
print(num2words(42, to="ordinal")) # forty-second
# Convert a number to year form
print(num2words(2024, to="year")) # two thousand and twenty-four
# Convert a number to currency form
print(num2words(42, to="currency")) # zero euro, forty-two cents
# Convert a number to words in a different language
print(num2words(42, lang="es")) # cuarenta y dos
Time complexity ofnum2words
: O(1)
Convert Numbers to Words online
Do you need to convert numbers to words online? Whether you want to write a cheque, spell out a large number, or validate your program result, you can use an online number to word converter tool to convert any number to its word representation.
Conclusion
In this blog post, I showed a technique for converting numbers to words in Python: utilizing the built-in num2words library. I hope you gained some fresh insight and knowledge from this post. Have fun with coding!