Format String: Only when value supplied

MRAB python at mrabarnett.plus.com
Tue Jun 24 07:09:00 EDT 2014


On 2014-06-24 10:18, Florian Lindner wrote:
> Hello,
>
> I have a format string like:
>
>   print "{:10} {:25} = {:6}   ({})".format(mod, name, value, description)
>
> description can be None. In this case I want to print an empty string (which
> can be achieved by replacing it with 'description or ""') and I want to omit
> the brackets. Is there a way to tell the format string to omit a part if an
> input variable is None?
>
You could strip the trailing brackets (and spaces too?) after
formatting:

     print "{:10} {:25} = {:6}   ({})".format(mod, name, value, 
description or "").rstrip("() ")

assuming, of course, that the value never ends with brackets.

> Another question: value can be bool. When I format value with just {} if
> prints True or False, when I use {:6} it prints 1 or 0. Is there a way to
> get pack to True / False?
>




More information about the Python-list mailing list