Returning a string from a boolean

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


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

>Dan Rawson <daniel.rawson.take!this!out!@asml.nl> 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'
>or
>   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)) ;-)

Regards,
Bengt Richter




More information about the Python-list mailing list