I\'m wondering if there is a quick and easy way to output ordinals given a number in python.
For example, given the number 1
, I\'d like to output
Here's a more general solution:
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")
Fixed for negative-inputs, based on eric.frederich's nice sol'n (just added abs
when using %
):
def ordinal(num):
return '%d%s' % (num, { 11: 'th', 12: 'th', 13: 'th'}.get(abs(num) % 100, { 1: 'st',2: 'nd',3: 'rd',}.get(abs(num) % 10, 'th')))
Here's a function I wrote as part of a calendar type of program I wrote (I'm not including the whole program). It adds on the correct ordinal for any number greater than 0. I included a loop to demo the output.
def ordinals(num):
# st, nums ending in '1' except '11'
if num[-1] == '1' and num[-2:] != '11':
return num + 'st'
# nd, nums ending in '2' except '12'
elif num[-1] == '2' and num[-2:] != '12':
return num + 'nd'
# rd, nums ending in '3' except '13'
elif num[-1] == '3' and num[-2:] != '13':
return num + 'rd'
# th, all other nums
else:
return num + 'th'
data = ''
# print the first 366 ordinals (for leap year)
for i in range(1, 367):
data += ordinals(str(i)) + '\n'
# print results to file
with open('ordinals.txt', 'w') as wf:
wf.write(data)
Here it is using dictionaries as either a function or as a lambda...
If you look at the dictionaries backwards you can read it as...
Everything ends in 'th'
...unless it ends in 1, 2, or 3 then it ends in 'st', 'nd', or 'rd'
...unless it ends in 11, 12, or 13 then it ends in 'th, 'th', or 'th'
# as a function
def ordinal(num):
return '%d%s' % (num, { 11: 'th', 12: 'th', 13: 'th' }.get(num % 100, { 1: 'st',2: 'nd',3: 'rd',}.get(num % 10, 'th')))
# as a lambda
ordinal = lambda num : '%d%s' % (num, { 11: 'th', 12: 'th', 13: 'th' }.get(num % 100, { 1: 'st',2: 'nd',3: 'rd',}.get(num % 10, 'th')))
I had to convert a script over from javascript where I had a useful fn that replicated phps date obj. Very similar
def ord(n):
return str(n)+("th" if 4<=n%100<=20 else {1:"st",2:"nd",3:"rd"}.get(n%10, "th"))
this tied in with my date styler:
def dtStylish(dt,f):
return dt.strftime(f).replace("{th}", ord(dt.day))
ps -I got here from another thread which was reported as a duplicate but it wasn't entirely since that thread also addressed the date issue
Or shorten David's answer with:
if 4 <= day <= 20 or 24 <= day <= 30:
suffix = "th"
else:
suffix = ["st", "nd", "rd"][day % 10 - 1]