substitute for c/java's ?:

Alex Martelli aleaxit at yahoo.com
Thu Jun 14 10:38:19 EDT 2001


"Jochen Riekhof" <jochen at riekhof.de> wrote in message
news:9ga8ue$7aj$07$1 at news.t-online.com...
    ...
> /**Utility which returns 'a' or 'an' for a given noun. */
> public static final String aan(String name) {
>     return ("aeiou".indexOf(name.toLowerCase().charAt(0))  < 0) ? "a" :
> "an";
> }
>
> which, compared to
>
> def aan(name):
>     """Utility which returns 'a' or 'an' for a given noun.
>     """
>     if string.lower(name[0]) in ('a','e','i','o','u'):
>         return 'an '
>     else:
>         return 'a '
>
> is not all that bad ;-). Of course you can use if else you like this
better.

If you like the horrid oneliner style above,

def aan(name):
    return ("a","an")[name[0].lower() in "aeiou"]

is the Python equivalent.  Why the H**K would one code
"in ('a','e','i','o','u')" rather than the exactly
equivalent "in 'aeiou'", for example?  I'd slightly
prefer the following non-strict-equivalent:
    return ("a","an")[name[0] in "aeiouAEIOU"]
but that doesn't substantially change the oneliner-
mentality behind such opaque coding...:-).


Alex






More information about the Python-list mailing list