2024-06-13 21:45:28 发布
网友
我想知道是否有一种快速简便的方法可以在python中输出给定数字的序号。
例如,给定数字1,我想输出"1st"、数字2、"2nd",等等。
1
"1st"
2
"2nd"
这是用来在面包屑轨迹中处理日期的
Home > Venues > Bar Academy > 2009 > April > 01
是当前显示的
我想要一些大致相同的东西
Home > Venues > Bar Academy > 2009 > April > 1st
下面是一个更通用的解决方案:
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
下面是一个更通用的解决方案:
或者缩短大卫的回答:
不确定5年前当你问这个问题时它是否存在,但是inflect包有一个函数来完成你想要的:
相关问题 更多 >
编程相关推荐