Returning a string from a boolean

Bengt Richter bokr at
Tue Aug 12 17:37:11 CEST 2003

On Tue, 12 Aug 2003 12:26:07 +0000 (UTC), Duncan Booth <duncan at> wrote:

>Dan Rawson <daniel.rawson.take!this!out!> wrote in
>news:bhalml$1012pe$1 at 
>> 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.

which you can ensure by str(bool(anyvar)) ;-)

Bengt Richter

More information about the Python-list mailing list