Have you ever needed to convert a number into its word equivalent in Python? Perhaps you're working on a project that requires generating reports, creating invoices, or even just having some fun with text manipulation. Converting integers to words can be a surprisingly useful and interesting task. This article explores various methods to achieve this, from simple lookups to more sophisticated library-based solutions.
Python's built-in str()
function can easily convert an integer to a string. However, it doesn't transform the value into its textual representation. For example, str(123)
yields "123"
, not "one hundred and twenty-three." This is where the problem lies and where custom solutions or external libraries come into play.
For a limited range of numbers, especially when performance is critical and the range is small, a direct lookup using lists or dictionaries can be an efficient solution.
numbers = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
def convert_to_word(n):
if 0 <= n < len(numbers):
return numbers[n]
else:
return "Number out of range"
print(convert_to_word(5)) # Output: five
print(convert_to_word(12)) # Output: Number out of range
This approach is straightforward but quickly becomes unwieldy for larger numbers.
For more flexibility, you can create a function that combines basic number words to construct larger ones. This involves handling units, teens, tens, and hundreds separately.
def int_to_en(num):
d = { 0 : 'zero', 1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four', 5 : 'five', 6 : 'six', 7 : 'seven', 8 : 'eight', 9 : 'nine', 10 : 'ten', 11 : 'eleven', 12 : 'twelve', 13 : 'thirteen', 14 : 'fourteen', 15 : 'fifteen', 16 : 'sixteen', 17 : 'seventeen', 18 : 'eighteen', 19 : 'nineteen', 20 : 'twenty', 30 : 'thirty', 40 : 'forty', 50 : 'fifty', 60 : 'sixty', 70 : 'seventy', 80 : 'eighty', 90 : 'ninety' }
k = 1000
m = k * 1000
b = m * 1000
t = b * 1000
assert(0 <= num)
if (num < 20):
return d[num]
if (num < 100):
if num % 10 == 0:
return d[num]
else:
return d[num // 10 * 10] + '-' + d[num % 10]
if (num < k):
if num % 100 == 0:
return d[num // 100] + ' hundred'
else:
return d[num // 100] + ' hundred and ' + int_to_en(num % 100)
if (num < m):
if num % k == 0:
return int_to_en(num // k) + ' thousand'
else:
return int_to_en(num // k) + ' thousand, ' + int_to_en(num % k)
if (num < b):
if (num % m) == 0:
return int_to_en(num // m) + ' million'
else:
return int_to_en(num // m) + ' million, ' + int_to_en(num % m)
if (num < t):
if (num % b) == 0:
return int_to_en(num // b) + ' billion'
else:
return int_to_en(num // b) + ' billion, ' + int_to_en(num % b)
if (num % t == 0):
return int_to_en(num // t) + ' trillion'
else:
return int_to_en(num // t) + ' trillion, ' + int_to_en(num % t)
raise AssertionError('num is too large: %s' % str(num))
print(int_to_en(1234567)) # Output: one million, two hundred and thirty-four thousand, five hundred and sixty-seven
This method requires more code but can handle a broader range of numbers. It’s a good exercise in understanding place values and string manipulation.
Several Python libraries are designed specifically for number-to-word conversion, offering robust and efficient solutions.
inflect
LibraryThe inflect
library is a powerful tool for handling English word forms, including number-to-word conversion.
import inflect
p = inflect.engine()
print(p.number_to_words(99)) # Output: ninety-nine
To install:
pip install inflect
num2words
Librarynum2words
is another excellent library focused solely on converting numbers to their word equivalents. It supports multiple languages and formatting options.
from num2words import num2words
print(num2words(1234, to='cardinal')) # Output: one thousand, two hundred and thirty-four
print(num2words(42, to='ordinal')) # Output: forty-second
To install:
pip install num2words
python-n2w
LibraryThis very simple library is useful, but has not been updated recently and may have issues with some versions of Python.
import n2w
print(n2w.convert(123)) # Output: one hundred and twenty-three
To install:
pip install n2w
The best approach depends on your specific needs:
inflect
or num2words
(Method 3)Most of these methods primarily focus on integers. To handle floating-point numbers, you can separate the integer and decimal parts and convert them individually.
def float_to_words(number):
integer_part = int(number)
decimal_part = round((number - integer_part) * 100) # Assuming 2 decimal places
integer_words = int_to_en(integer_part)
decimal_words = int_to_en(decimal_part)
return f"{integer_words} point {decimal_words}"
print(float_to_words(123.45)) # Output: one hundred and twenty-three point forty-five
Converting integers to words in Python can be achieved through various methods, each with its own trade-offs. Whether you opt for a simple lookup table, a custom-built function, or a dedicated library, understanding the underlying principles will help you choose the best approach for your project. By using libraries like inflect
and num2words
, you can convert these numbers easily. Remember to consider the range of numbers, performance requirements, and desired level of customization when making your decision.