当前位置: 首页 > news >正文

[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 datetoday = 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

http://www.gsyq.cn/news/142716.html

相关文章:

  • 大型数控折弯机厂家哪家好?2025大型折弯机厂家实力榜 - 栗子测评
  • 2025森林消防装备厂家与灭火装备厂家的硬核实力盘点 - 栗子测评
  • 在c++中使用命令行解析器(C++11)(CLI11开源库)
  • python基于组件化开发的医院人力资源管理系统的设计与实现_ao7y58lr_Pycharm vue flask
  • 学术革命新引擎:书匠策AI如何重塑期刊论文写作生态?
  • pycharm如何设置uvicorn debug
  • 2025年球墨铸铁管厂家哪家好?全场景适配推荐,多维测评权威榜单 - AIEO
  • 书匠策AI:本科论文的“全能导航仪”,解锁学术新技能,引领未来科研风尚
  • Spec模式赋能百度网盘场景提效
  • 2025四川餐巾纸/卫生纸/抽纸/卷纸/擦手纸工厂选择指南 - 2025年品牌推荐榜
  • python基于flask的体育运动健身房会员管理系统的设计与实现_s11mrt5m_Pycharm vue django
  • 全域信源决胜:GEO优化服务商优选指南 - 品牌推荐排行榜
  • 深耕GEO优化赛道:优质服务商甄选指南与商业增长赋能 - 品牌推荐排行榜
  • python基于小程序的讲座讲话演讲稿共享及检索系统_813053yp_Pycharm vue flask
  • 全网免费无广!这款台球游戏竟有最真实的物理引擎
  • 在压力下保持创造力和解决问题的能力的秘诀
  • HarmonyOS 5开发从入门到精通(二):ArkTS语言基础与声明式UI
  • 2025年最新固废处理行业观察报告:5家优质企业的技术实践与场景布局 - 深度智识库
  • 从GPU到主板:一场被忽视的AI硬件革命
  • 5个常见问题解答有关YashanDB数据库的优势
  • 2025年大模型学习必备指南:零基础到实战专家,一篇文章带你探索进阶之路!大模型学习路线
  • 大文件上传面试回答要点
  • 视频号直播怎么搭配提词器使用?全流程新手攻略
  • 真空发生器哪家好?2025真空发生器生产厂家好评红榜 - 栗子测评
  • 打工人年底必须知道的知识!十三薪vs年终奖
  • 怎么在windows上给文件夹添加comment注释
  • 2025年12月23日--rabbitMQ的使用
  • 2025年12月塑料敞口塑料圆桶,酸泡菜腌制塑料圆桶,养殖塑料圆桶厂家推荐:行业测评与选择指南 - 品牌鉴赏师
  • anything-llm镜像是否支持GraphQL接口?
  • 在Go架构设计中引入Java业务链及调度思想