Tertiary Operation
Carsten Haese
carsten at uniqsys.com
Tue Oct 17 09:43:43 EDT 2006
On Tue, 2006-10-17 at 09:30, abcd wrote:
> x = None
> result = (x is None and "" or str(x))
>
> print result, type(result)
>
> ---------------
> OUTPUT
> ---------------
> None <type 'str'>
The "condition and result1 or result2" trick only works if result1 is an
expression with a True boolean value. The empty string has a false
boolean value.
You could force result1 to have a true boolean value by sticking it into
a list thusly:
result = (x is None and [""] or [str(x)])[0]
But that's ugly. Use Python 2.5 where there is a true conditional
expression or find another way to solve your problem.
-Carsten
More information about the Python-list
mailing list