Single format descriptor for list

Ben Finney ben+python at benfinney.id.au
Wed Jan 20 05:05:35 EST 2016


Paul Appleby <pap at nowhere.invalid> writes:

> In BASH, I can have a single format descriptor for a list:
> […]
> Is this not possible in Python?

Not as such; you'll need to treat items differently from sequences of
items.

> Using "join" rather than "format" still doesn't quite do the job:

Right, ‘str.join’ is meant for making a new string by joining
substrings.

What you want is to take each item and *append* some text. You can do
that by constructing a sequence dynamically::

    >>> values = range(4, 8)
    >>> print("\n".join(
    ...         "{:d}th".format(item) for item in values))
    4th
    5th
    6th
    7th

> Is there an elegant way to print-format an arbitrary length list?

In general, if you can figure out an operation you'd like to perform on
each item of a sequence, you may try a generator expression to express
the transformed sequence.

In the above example:

* Express the transformation of the sequence: format each number with
  "{:d}th". This can be done with a generator expression, producing an
  iterable.

* Figure out what to do to the transformed sequence: join them all
  together with "\n" between each item. This can be done by passing the
  transformed iterable as the argument to ‘str.join’.

The built-in collection types – dict, list, set, generator, etc. – are
very powerful in Python because of the built-in syntax for expressing
and interrogating and consuming them. Learning to use them is an
important tool in avoiding more complex and error-prone code.

-- 
 \     “[F]reedom of speech does not entail freedom to have your ideas |
  `\    accepted by governments and incorporated into law and policy.” |
_o__)                                   —Russell Blackford, 2010-03-06 |
Ben Finney




More information about the Python-list mailing list