[Tutor] correcting an Active State Recipe for conversion to ordinal

Serdar Tumgoren zstumgoren at gmail.com
Thu Feb 4 21:51:47 CET 2010

```> If you want value % 100/10 to give the same result in Python 2.6 and
> Python 3 you can use value % 100//10 which will always use integer
> division.
>

Kent, thanks for anticipating this. I actually was struggling to
figure out how to update the division and wasn't certain how.

Below is the fully revised code based on all of your suggestions. At
some point I'll try my hand at an update that handles negative
integers as well.

Meantime, thanks to everyone for the help! As always, you never fail
to come through!

def ordinal(value):
"""
Converts a *postivie* integer or its string representation
to an ordinal value.

>>> for i in range(1,13):
...     ordinal(i)
...
u'1st'
u'2nd'
u'3rd'
u'4th'
u'5th'
u'6th'
u'7th'
u'8th'
u'9th'
u'10th'
u'11th'
u'12th'

>>> for i in (100, '111', '112',1011):
...     ordinal(i)
...
u'100th'
u'111th'
u'112th'
u'1011th'

"""
try:
value = int(value)
except ValueError:
return value

if value % 100//10 != 1:
if value % 10 == 1:
ordval = u"%d%s" % (value, "st")
elif value % 10 == 2:
ordval = u"%d%s" % (value, "nd")
elif value % 10 == 3:
ordval = u"%d%s" % (value, "rd")
else:
ordval = u"%d%s" % (value, "th")
else:
ordval = u"%d%s" % (value, "th")

return ordval

if __name__ == '__main__':
import doctest
doctest.testmod()
```