[python] add st, nd, rd and th to day of the month

 

You are asking for ordinal day suffixes: 1st, 2nd, 3rd, 4th, … including the exception for 11, 12, 13.

This is a classic edge-case problem and should be implemented deterministically, not with ad-hoc conditionals.


Correct rule (non-negotiable)

  • If the day is 11, 12, or 13"th"

  • Otherwise:

    • Ends in 1 → "st"

    • Ends in 2 → "nd"

    • Ends in 3 → "rd"

    • Everything else → "th"


Canonical Python implementation

def ordinal(day: int) -> str:
    if 11 <= day % 100 <= 13:
        suffix = "th"
    else:
        suffix = {1: "st", 2: "nd", 3: "rd"}.get(day % 10, "th")
    return f"{day}{suffix}"

Examples

for d in range(1, 32):
    print(ordinal(d))

Output (excerpt):

1st
2nd
3rd
4th
...
10th
11th
12th
13th
14th
...
21st
22nd
23rd
24th
...
31st

Why this is the correct approach

  • Uses mod 100 to correctly catch 11–13

  • Uses mod 10 only when safe

  • Avoids fragile chains of if/elif

  • Easily testable

  • Works for any positive integer, not just calendar days


If you want it embedded in datetime

from datetime import date

today = date.today()
print(ordinal(today.day))

Blunt advice

If you ever see code that checks if day == 1, elif day == 2, etc., it is wrong, unscalable, and unacceptable in professional Python.

If you want variants (locale-aware, zero-padded, or formatted dates like March 21st, 2025), say so.

 

 

from ChatGPT

posted @ 2025-12-23 18:32  profesor  阅读(3)  评论(0)    收藏  举报