Tertiary Operation

Tim Chase python.list at tim.thechases.com
Tue Oct 17 15:48:58 CEST 2006


> x = None
> result = (x is None and "" or str(x))
> 
> print result, type(result)
> 
> ---------------
> OUTPUT
> ---------------
> None <type 'str'>
> 
> 
> y = 5
> result = (y is 5 and "it's five" or "it's not five")
> 
> print result
> 
> -------------
> OUTPUT
> -------------
> it's five
> 
> ...what's wrong with the first operation I did with x?  I was expecting
> "result" to be an empty string, not the str value of None.

An empty string evaluates to False, so it then continues to the 
other branch.  Either of the following should suffice:

	# return a non-empty string
	x is None and "None" or str(x)

	# invert the logic and return
	# something in the "and" portion
	x is not None and str(x) or ""

There are more baroque ways of writing the terniary operator in 
python (although I understand 2.5 or maybe python 3k should have 
a true way of doing this).  My understanding is that one common 
solution is something like

	{True: "", False: str(x)}[x is None]

-tkc






More information about the Python-list mailing list