Python snippet: ordinalth(n)
Blogged so I don’t lose it (blogging as external memory):
def ordinalth(n):
""" 1 => 1st, 2 => 2nd etc """
last = n - n / 10 * 10
if last == 1:
return '%dst' % n
if last == 2:
return '%dnd' % n
if last == 3:
return '%drd' % n
return '%dth' % n
Update: See comments for improved version.
Nice trick Simon, but i would remove if's completely:
def ordinalth2(n):
t = '%dth', '%dst', '%dnd', '%drd', '%dth', '%dth', '%dth' , '%dth' , '%dth', '%dth'
last = n - (n / 10 * 10)
return t[last] % n
if you pass 21 to ordinalth and ordinalth they both retiurn "21st", mmm...deelan - 8th October 2003 15:42 - #
talon - 8th October 2003 15:44 - #
Sam Ruby - 8th October 2003 15:58 - #
Improved version, taking the above comments in to account:
Test code:
(I've finally enabled the <pre> tag)
Simon Willison - 8th October 2003 16:11 - #
if (n % 100) in (11, 12, 13):Curioso - 8th October 2003 16:24 - #
Simon Willison - 8th October 2003 16:30 - #
You missed 111th. Untested, but should work (just need to mod 100 for the 11th..13th):
def ordinalth(n): t = 'th st nd rd th th th th th th'.split() if n % 100 in (11, 12, 13): #special case return '%dth' % n return str(n) + t[n % 10]Brian Harnish - 8th October 2003 16:32 - #
DeanG - 8th October 2003 17:11 - #
def inttoord(i): ordinal = [ ('th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th'), ('th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th')] ones = i % 10 tens = (i % 100) / 10 return str(i) + ordinal[tens==1][ones]Bill - 8th October 2003 17:32 - #
ryandjess@aaaaaaatt.net - 29th December 2003 15:40 - #
Jason R. Coombs - 14th May 2004 17:22 - #