日期顺序输出?

2024-06-13 21:45:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道是否有一种快速简便的方法可以在python中输出给定数字的序号。

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

这是用来在面包屑轨迹中处理日期的

Home >  Venues >  Bar Academy >  2009 >  April >  01 

是当前显示的

我想要一些大致相同的东西

Home >  Venues >  Bar Academy >  2009 >  April >  1st

Tags: 方法home轨迹bar数字面包屑academyapril
3条回答

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

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")

或者缩短大卫的回答:

if 4 <= day <= 20 or 24 <= day <= 30:
    suffix = "th"
else:
    suffix = ["st", "nd", "rd"][day % 10 - 1]

不确定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

相关问题 更多 >