日期序数输出?

Mez*_*Mez 20 python

我想知道在python中给出一个数字是否有一种快速简便的输出序数的方法.

例如,给定数字1,我想输出"1st",数字2,"2nd"等等等.

这是用于处理面包屑路径中的日期

Home >  Venues >  Bar Academy >  2009 >  April >  01 
Run Code Online (Sandbox Code Playgroud)

是目前显示的

我想要有一些东西

Home >  Venues >  Bar Academy >  2009 >  April >  1st
Run Code Online (Sandbox Code Playgroud)

Abi*_*ern 37

或者缩短大卫的回答:

if 4 <= day <= 20 or 24 <= day <= 30:
    suffix = "th"
else:
    suffix = ["st", "nd", "rd"][day % 10 - 1]
Run Code Online (Sandbox Code Playgroud)

  • 我不知道"if x <= y <= z"的语法,无法相信它会起作用并尝试过.看起来我应该重新阅读Python doc** (7认同)
  • 没错,但是OP询问了序数日期.从YAGNI开始,选择更短,更优雅的解决方案来满足他的需求会更好,即使它不是一般化的.如果有人想要一个通用的解决方案,你的确很好,尽管我可能会使用列表而不是elseifs. (4认同)

CTT*_*CTT 29

这是一个更通用的解决方案:

def ordinal(n):
    if 10 <= n % 100 < 20:
        return str(n) + 'th'
    else:
       return  str(n) + {1 : 'st', 2 : 'nd', 3 : 'rd'}.get(n % 10, "th")
Run Code Online (Sandbox Code Playgroud)


alu*_*ach 12

5年前当你问这个问题时不确定它是否存在,但是inflect包有一个功能来完成你正在寻找的东西:

>>> import inflect
>>> p = inflect.engine()
>>> for i in range(1,32):
...     print p.ordinal(i)
...
1st
2nd
3rd
4th
5th
6th
7th
8th
9th
10th
11th
12th
13th
14th
15th
16th
17th
18th
19th
20th
21st
22nd
23rd
24th
25th
26th
27th
28th
29th
30th
31st
Run Code Online (Sandbox Code Playgroud)


Car*_*arl 5

这些天我会使用 Arrow http://arrow.readthedocs.io/en/latest/(这在 09 年肯定不存在)

>>> import arrow
>>> from datetime import datetime
>>> arrow.get(datetime.utcnow()).format('Do')
'27th'
Run Code Online (Sandbox Code Playgroud)