当前位置: 首页 > 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.jsqmd.com/news/130121/

相关文章:

  • 物品复活平台开发总结:软件工程视角下的实践与反思
  • AI应用开发利器:8款主流向量数据库盘点与实践建议,让你轻松应对各种应用场景!
  • Laravel项目学习:创建项目并执行
  • 期末考试04
  • 直播预告 | 极致优化:为MoE大模型跑出昇腾加速度
  • RAG系列(五)生产部署、成本优化与系统评估
  • AI技术的哲学思考:大模型如何实现记忆遗传?记忆蒸馏、机械飞升方案和软调控方式优劣探讨!
  • 中山留学中介哪家好?中山市粤教国际教育深度分析 - 栗子测评
  • 直播预告 | 从学术源头到产业活水:CANN开源生态的双向赋能新范式
  • (三)Stable Diffusion 3.5 与 ComfyUI
  • 单片机 IO 翻转应用
  • 执业医师考试培训:甄选靠谱机构,笃行医考备考之路 - 资讯焦点
  • 直播预告 | 独行快,众行远:CANN开源生态的共识、共振与共行
  • 月薪15K到25K的关键一跃:AI时代,产品经理是恐慌失业,还是迎来新机遇?
  • 7个ColorOS宝藏功能!ToDesk远控太懂我!
  • 2025最新园林景观、景观设计、景观施工、绿化、景观工程推荐至大园林景观:三维服务体系,铸就空间美化专家 - 全局中转站
  • 期末部分复习基础概念题
  • 从入门到实践:玩转分布式链路追踪利器SkyWalking
  • 在深圳学无人机?2025深圳无人机培训机构推荐清单收好 - 栗子测评
  • leetcode 2054(排序 + 单调栈,通用做法是 DP)
  • “星河璀璨,艺术远航”首届中华书画瓷器艺术太空邀请展在京发布
  • 2025国内幕墙铝单板厂家有哪些:氟碳喷涂铝单板厂家大盘点 - 栗子测评
  • pycharm如何设置uvicorn debug
  • 2025国内幕墙铝单板厂家有哪些:氟碳喷涂铝单板厂家大盘点 - 栗子测评
  • 从代码补全到项目交付:MonkeyCode如何重塑你的全流程开发体验
  • 智能体在车联网中的应用:第14天 卷积神经网络(CNN)专精:从卷积原理到LeNet-5实战车辆图像分类
  • 冷冻研磨机哪个品牌好,国产新起之秀飞驰(北京)/净信突出重围 - 品牌推荐大师1
  • GEO优化的价值锚点:DeepSeek及多平台优化服务商甄选指南 - 品牌推荐排行榜
  • 4G工业网关实现PLC数据采集与HTTP协议上报
  • 达尔文12号在哪买:效率提80%!一键直达抢购口揭秘 - 品牌测评家