Cool Python Function
Posted by Stephen on October 3, 2006 in Programming, Stuff
I’m not sure that others would find this interesting, but I’m posting it anyway in case I need this later. While working on a Python script, I needed something that would generate the proper suffixes to make ordinal numbers like 1st, 2nd, and 3rd. Since some markup schemes allow you make the suffix a superscript, I wanted a function that only generates the suffix, so that I can use the function with multiple markup conventions. I poked around in the module documentation and didn’t find anything useful, so I wrote this:
def get_suffix(num):
special_suffixes = { '1': 'st', '2': 'nd', '3': 'rd' }
default_return = 'th'
digits = str(abs(num)) # To work with negative numbers
last_digit = digits[-1:]
if last_digit in special_suffixes.keys():
# Numbers that end in 11, 12, and 13 just get 'th'
if len(digits) == 1 or digits[-2] != '1':
default_return = special_suffixes[last_digit]
return default_return
Short and easy.
Write a Comment on Cool Python Function
Comments on Cool Python Function are now closed.