I'm relatively new to Python (actively coding for 2 months), and I just coded a simple function that converts an integer to a string and adds the English 2-character string as a suffix that traditionally indicates the integer's order in a list. I quickly coded something that works great, but it is killing me because I just know there is a more pythonic way to do this.
So what I'm trying to achieve is:
i_to_suffix_str(1) => '1st'
i_to_suffix_str(11) => '11th'
i_to_suffix_str(33) => '33rd'
i_to_suffix_str(142) => '142nd'
...etc.
My code (which feels neither concise nor Pythonic):
def i_to_suffix_str(i):
sig_digits = i % 100
if sig_digits > 3 and sig_digits < 21:
suffix = 'th'
elif (sig_digits % 10) == 1:
suffix = 'st'
elif (sig_digits % 10) == 2:
suffix = 'nd'
elif (sig_digits % 10) == 3:
suffix = 'rd'
else:
suffix = 'th'
return str(i) + suffix
I've tasted of the ways of Python, and I know that there must be a better way. ...any takers?