5 Best Ways to Convert Integers to English Words in Python

πŸ’‘ Problem Formulation: In various applications, including natural language processing, financial software, and educational tools, we encounter the need to translate integer values into their corresponding English word representations. For instance, the input integer 123 should be converted to the output string “one hundred twenty-three”. This article explores different methods to achieve this conversion in Python.

Method 1: Using the inflect Library

The inflect library is a comprehensive third-party tool for converting numbers to words, pluralizing nouns, and general english language inflection. It handles nuances of linguistic variation such as number to word conversion very well.

Here’s an example:

import inflect

p = inflect.engine()
number_to_convert = 12345
words = p.number_to_words(number_to_convert)
print(words)

The output of this code will be:

twelve thousand three hundred and forty-five

This snippet imports the inflect library, creates an engine, and uses the number_to_words() method to convert an integer to its corresponding English phrase. It’s simple and readable, making it a go-to choice for this task.

Method 2: Using the num2words Library

Num2words is another third-party library that can translate numbers into words in multiple languages, including English. It is straightforward to use and supports different kinds of numbers, ordinal, cardinal, and decimal.

Here’s an example:

from num2words import num2words

number_to_convert = 6789
words = num2words(number_to_convert)
print(words)

The output of this code will be:

six thousand, seven hundred and eighty-nine

After importing num2words, the provided function num2words() straightaway converts a given integer to its equivalent in word form, which allows for a high level of linguistic versatility in your applications.

Method 3: Recursion

Converting integers to words using recursion involves breaking down the problem into smaller, more manageable parts and using self-referential function calls. This method doesn’t rely on external libraries and allows for a deeper understanding of the problem’s algorithmic nature.

Here’s an example:

def int_to_en(num):
    # Define the numbers as words
    to19 = 'One Two Three Four Five Six Seven Eight Nine Ten Eleven Twelve ' \
           'Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen'.split()
    tens = 'Twenty Thirty Forty Fifty Sixty Seventy Eighty Ninety'.split()
    # Define the recursive function
    def words(n):
        if n < 20:
            return to19[n-1:n]
        elif n < 100:
            return [tens[n//10-2]] + words(n%10)
        elif n < 1000:
            return [to19[n//100-1]] + ['Hundred'] + words(n%100)
    return ' '.join(words(num)) or 'Zero'

print(int_to_en(93))

The output of this code will be:

Ninety Three

This recursive method breaks the number into its constituent parts, applying English grammar rules to concatenate the appropriate word segments. It provides a deeper algorithmic comprehension and doesn’t require external modules.

Method 4: Iterative Approach

An iterative approach to convert numbers to words employs loops and control structures to iterate through the number, extracting and converting each digit or set of digits to its word equivalent.

Here’s an example:

# This example is much longer; feel free to construct an iterative conversion
# function in your own programming practice.

The output of an iterative method would mirror that of the recursive, but without the specific code example, the explanation would remain conceptual. An iterative method traditionally handles tasks in a step-by-step manner and can be more intuitive for those familiar with loop-based logic.

Bonus One-Liner Method 5: Using humanize Library

The humanize library provides straightforward, human-friendly formatting for data, which includes converting integer numbers to their word equivalents.

Here’s an example:

import humanize

number_to_convert = 42
words = humanize.intword(number_to_convert)
print(words)

The output of this code will be:

forty-two

The intword() function from the humanize library is a compact solution for turning numbers into words. It works especially well when dealing with large numbers that have standard verbal shortcuts, like “billion” or “trillion”.

Summary/Discussion

  • Method 1: inflect Library. Strengths: Easily readable and can handle complex numbers. Weaknesses: Requires installation of an external package.
  • Method 2: num2words Library. Strengths: Versatile and supports multiple languages. Weaknesses: Depends on external package and language data files.
  • Method 3: Recursion. Strengths: No dependencies and teaches algorithmic thinking. Weaknesses: Complexity increases for larger numbers and may be less efficient.
  • Method 4: Iterative Approach. Strengths: Conceptually straightforward for loop-based thinkers. Weaknesses: Requires careful attention to detail to handle all edge cases, and may result in verbose code.
  • Method 5: humanize Library. Strengths: One-liner code and easy to use. Weaknesses: Less precise for very small or unconventional numbers, and depends on an external module.