0

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?

Arnaldo C
  • 13
  • 2

2 Answers2

0

Perhaps use a dictionary to trim it down a bit

lst = [1, 11, 20, 33, 44, 50, 142]
sigs = {1: 'st', 2: 'nd', 3: 'rd'}
for i in lst:
    if 3 < i < 21:
        print(f'{i}th')
    elif int(str(i)[-1]) in sigs.keys():
        print(f'{i}{sigs[int(str(i)[-1])]}')
    else:
        print(f'{i}th')
# 1st 11th 20th 33rd 44th 50th 142nd
vash_the_stampede
  • 4,590
  • 1
  • 8
  • 20
0

You could use a dictionary combined with Python ternary operator, for instance:

def i_to_suffix_str(i):
    sig_digits = i % 100
    suffixes = {1: 'st', 2: 'nd', 3: 'rd'}
    suffix = 'th' if 3 < sig_digits < 21 else suffixes.get(sig_digits % 10, 'th')
    return str(i) + suffix

print(i_to_suffix_str(1))
print(i_to_suffix_str(11))
print(i_to_suffix_str(33))
print(i_to_suffix_str(142))

Output

1st
11th
33rd
142nd
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76