Returning a string from a boolean
Duncan Booth
duncan at NOSPAMrcp.co.uk
Tue Aug 12 08:26:07 EDT 2003
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.
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list