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