-2

For example:

I have a list = ['0','1','2','3','4']

say I want to print "The 1st element is 0" or " 3rd element is 2". Essentially, how do I add a st or nd or th at the end of the number?

1st, 2nd,3rd,etc

I think using a case-by-case or if-elif-else would be too much work. Is there any other way of doing this?

Thank you

1 Answers1

0

You could use a dictionary to avoid the need for the if-elif-else, for example:

def ordinal(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


lst = ['0', '1', '2', '3', '4']

for i, e in enumerate(lst, 1):
    print('The {} element is {}'.format(ordinal(i), e))

Output

The 1st element is 0
The 2nd element is 1
The 3rd element is 2
The 4th element is 3
The 5th element is 4

The ordinal function is equivalent to:

def ordinal_with_if(i):
    sig_digits = i % 100
    if 3 < sig_digits < 21:
        return str(i) + 'th'
    elif sig_digits % 10 == 1:
        return str(i) + 'st'
    elif sig_digits % 10 == 2:
        return str(i) + 'nd'
    elif sig_digits % 10 == 3:
        return str(i) + 'rd'
    else:
        return str(i) + 'th'
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76