As a Python software engineer, it’s important to have a solid understanding of how to manipulate and format data.

One common task that comes up in many projects is adding the correct suffix to an integer, such as “1st”, “2nd”, “3rd”, and “4th”.

In this article, we’ll explore a few different ways to accomplish this task in Python.

The first method we’ll discuss is using a simple if-else block to check the last digit of the integer and add the appropriate suffix. This method works well for small numbers, but can quickly become unwieldy for larger numbers.

Here’s an example:

def add_suffix(num):
    if num % 10 == 1:
        return str(num) + "st"
    elif num % 10 == 2:
        return str(num) + "nd"
    elif num % 10 == 3:
        return str(num) + "rd"
    else:
        return str(num) + "th"

Another method is using a switch case like approach to check the last digit of the integer and add the appropriate suffix.

This method works well for small numbers, but this can also quickly become unwieldy for larger numbers. Here’s an example:

def add_suffix(num):
    suffixes = {1: "st", 2: "nd", 3: "rd"}
    if num % 100 in (11, 12, 13):
        return str(num) + "th"
    return str(num) + suffixes.get(num % 10, "th")

A more efficient and elegant approach is to use the built-in Python module num2words. This module can convert numbers to words, and also includes a ordinal() function that will add the correct suffix to integers. Here’s an example of how to use it:

from num2words import num2words
def add_suffix(num):
    return num2words(num, to='ordinal')

In this article, we’ve looked at three different ways to add the correct suffix to an integer in Python. The first method uses a simple if-else block to check the last digit of the integer, the second one uses a switch case like approach and the last one uses the built-in num2words module. Each method has its own advantages and disadvantages, so it’s important to choose the one that works best for your specific use case.

Overall the last method using num2words module is the most efficient and elegant way to handle this problem. It is recommended to use this method when you want to add suffixes to integers in your python application.