Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #73538 > unrolled thread
| Started by | Ned Batchelder <ned@nedbatchelder.com> |
|---|---|
| First post | 2014-06-24 06:28 -0400 |
| Last post | 2014-06-24 06:28 -0400 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: Format String: Only when value supplied Ned Batchelder <ned@nedbatchelder.com> - 2014-06-24 06:28 -0400
| From | Ned Batchelder <ned@nedbatchelder.com> |
|---|---|
| Date | 2014-06-24 06:28 -0400 |
| Subject | Re: Format String: Only when value supplied |
| Message-ID | <mailman.11213.1403605711.18130.python-list@python.org> |
On 6/24/14 5:18 AM, 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?
.format() is not that sophisticated. One option is to build your string
in pieces like this:
if description:
nice_description = " ({})".format(description)
else:
nice_description = ""
print "{:10} {:25} = {:6}{}".format(mod, name, value, nice_description)
Another option is to use a real templating engine like Mako or Jinja
that lets you use conditionals.
>
> 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?
You can force it to be a string with "{!s:6}"
--
Ned Batchelder, http://nedbatchelder.com
Back to top | Article view | comp.lang.python
csiph-web