Returning a string from a boolean
daniel.rawson.take!this!out! at asml.nl
Tue Aug 12 15:22:02 CEST 2003
Duncan Booth wrote:
> Dan Rawson <email@example.com> wrote in
> news:bhalml$1012pe$1 at ID-122008.news.uni-berlin.de:
>>In Perl I can do this with the ternary 'if'
>>(bVar) ? 'True' : 'False'
>>Is there a simpler way in Python??
>>If it makes a difference, I'm using 2.2.2 (on Solaris) with no chance
>>of going to 2.3 in the near future <g>; I know that some of this has
>>changed in 2.3.
> Python 2.2 and earlier, the shortest way is:
> return bVar and 'True' or 'False'
> return ('True','False')[not bVar]
> Both of the above will test the truth value of bVar, so for example an
> empty string or empty list will return False. Personally, I would go for
> your original function as combining clarity with reasonable but not
> excessive brevity.
> In Python 2.3, str(bVar) will give you 'True' or 'False' as appropriate,
> but only if bVar is a bool.
OK, thanks. I tend to use the one-line version because I can stick it inside (for example) a 'print' statement.
More information about the Python-list