compound statement from C "<test>?<true-val>:<false-val>"
Jussi Salmela
tiedon_jano at hotmail.com
Sat Feb 3 06:56:39 EST 2007
bearophileHUGS at lycos.com kirjoitti:
> Jussi Salmela:
>> In this particular case you don't need the ternary operator:
>> print "I saw %d car%s\n" % (n, ("", "s")[n != 1])
>
> The last newline is probably unnecessary. This seems be a bit more
> readable:
> print "I saw", n, "car" + ("", "s")[n != 1]
>
> With Python 2.5 this looks better:
> print "I saw", n, "car" + ("" if n == 1 else "s")
>
> Or the vesion I like better:
> print "I saw", n, ("car" if n == 1 else "cars")
>
> Those () aren't necessary, but they help improve readability, and
> avoid problems with operator precedence too. That if has a quite low
> precedence.
>
> Bye,
> bearophile
>
This is getting weird but here's 2 more in the spirit of
"who needs the ternary operator - I don't!". And I'm starting to
wonder what the 'obvious way' (as in 'Zen of Python') to write
this would be.
print "I saw %d car%s" % (n, {1:''}.get(n==1, 's'))
print "I saw %d car%s" % (n, 's'*(n!=1))
Cheers,
Jussi
More information about the Python-list
mailing list