George V. Reilly

Python Print Formatting

On Stack­Over­flow, someone wanted to print triangles in Python in an M-shape. Various clumsy solutions were offered.

Here’s mine which uses the left- and right-jus­ti­fi­ca­tion features of str.format.

Putting them together:

.. code:: pycon
>>> WIDTH = 4
>>>
>>> for a in range(1, WIDTH+1):
...     print("{0:<{1}}{0:>{1}}".format('*' * a, WIDTH))
...
*      *
**    **
***  ***
********

Handy references: PyFormat and Python String Format Cookbook.

blog comments powered by Disqus
Review: Star Fall » « Christmas Puddings