r/PythonLearning • • May 06 '26

Can I do this more efficiently?

Post image

I am working through Al Sweigart’s book ‘Python Programming Exercises, Gently Explained’ and just completed exercise 6:
“In English, ordinal numerals have suffixes such as the "th" in "30th" or "nd" in "2nd". Write an ordinalSuffix() function with an integer parameter named number and returns a string of the number with its ordinal suffix. For example, ordinalSuffix(42) should return the string
'42nd'.”
Can I improve my solution? I feel there must be a more pythonic way of doing this, I’m not very happy with converting the integer to a string and then to a list.

153 Upvotes

47 comments sorted by

View all comments

6

u/Kevdog824_ May 06 '26

Something like this could work

def ordinalSuffix(number: int) -> str:
    s = str(number).zfill(2)
    match s[-2], s[-1]:
        case “1”, _:
            return “th”
        case _, “1”:
            return “st”
        case _, “2”:
            return “nd”
        case _, “3”:
            return “rd”
        case _, _:
            return “th”

1

u/TheKiller36_real May 10 '26

minor improvement suggestion:

s = f"{number:02}"

and the last match arm:

case _: