[Tutor] Printing multi-line variables horizontally
Steven D'Aprano
steve at pearwood.info
Sat Aug 9 05:28:08 CEST 2014
On Fri, Aug 08, 2014 at 01:50:53AM -0700, Greg Markham wrote:
[...]
> So, how would I get this to display horizontally?
>
> Like so...
> .-----. .-----.
> | | |o |
> | o | | |
> | | | o|
> `-----' `-----'
Nice question! I recommend that you try to solve the problem yourself,
if you can, but once you've given it a good solid try, you can have a
look at my solution and see if you can understand it. Feel free to ask
questions as needed.
S
P
O
I
L
E
R
S
P
A
C
E
.
.
.
N
O
C
H
E
A
T
I
N
G
def expand(rows, width, height):
"""Expand a list of strings to exactly width chars and height rows.
>>> block = ["abcde",
... "fgh",
... "ijklmno"]
>>> result = expand(block, 8, 4)
>>> for row in result:
... print (repr(row))
...
'abcde '
'fgh '
'ijklmno '
' '
"""
if len(rows) > height:
raise ValueError('too many rows')
extra = ['']*(height - len(rows))
rows = rows + extra
for i, row in enumerate(rows):
if len(row) > width:
raise ValueError('row %d is too wide' % i)
rows[i] = row + ' '*(width - len(row))
return rows
def join(strings, sep=" "):
"""Join a list of strings side-by-side, returning a single string.
>>> a = '''On peut rire de tout,
... mais pas avec tout le
... monde.
... -- Pierre Desproges'''
>>> b = '''You can laugh about
... everything, but not
... with everybody.'''
>>> values = ["Quote:", a, b]
>>> print (join(values, sep=" ")) #doctest:+NORMALIZE_WHITESPACE
Quote: On peut rire de tout, You can laugh about
mais pas avec tout le everything, but not
monde. with everybody.
-- Pierre Desproges
"""
blocks = [s.split('\n') for s in strings]
h = max(len(block) for block in blocks)
for i, block in enumerate(blocks):
w = max(len(row) for row in block)
blocks[i] = expand(block, w, h)
result = []
for row in zip(*blocks):
result.append(sep.join(row))
return '\n'.join(result)
--
Steven
More information about the Tutor
mailing list