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

Serdar Tumgoren zstumgoren at gmail.com
Thu Feb 4 19:30:48 CET 2010


On Thu, Feb 4, 2010 at 1:21 PM, Serdar Tumgoren <zstumgoren at gmail.com> wrote:
>> Perhaps the code on activestate is not a correct copy of what you are
>> running? The conditional at line 23 extends all the way to line 35 -
>> the end of the function - so if value % 100/10 == 1 no more code is
>> executed and None is returned.
>>
>
> Here is the code that I'm running locally (hopefully the formatting
> doesn't get screwed up):
>
> def ordinal(value):
>    """
>    Converts an integer to it's ordinal as a string.
>    For example 1 to "1st", 2 to "2nd", 3 to "3rd", etc.
>    """
>    try:
>        value = int(value)
>    except ValueError:
>        return value
>
>    if value % 100/10 <> 1:
>        if value % 10 == 1:
>            ord = u"%d%s" % (value, "st")
>            return ord
>        elif value % 10 == 2:
>            ord = u"%d%s" % (value, "nd")
>            return ord
>        elif value % 10 == 3:
>            ord = u"%d%s" % (value, "rd")
>            return ord
>        else:
>            ord = u"%d%s" % (value, "th")
>            return ord
>    else:
>        ord = u"%d%s" % (value, "th")
>        return  ord
>
Geez -- I think I found the (now-obvious) mistake. If you compare the
above to the ActiveState recipe, it's obvious that I forgot to copy
over the final, outer "else:" clause.

Could you all indulge me one last time and tell me if the above
version works for you? If so, I'll update the recipe to spare others a
similar headache.

And yes, I get the idiot award for the day...

Regards,

Serdar


More information about the Tutor mailing list