Search code examples
pythonpython-3.xfor-loopformat

Simplify .format printing in Python


I'm trying to print out the following:

-----------------------------
|             |             |
|             |      P      |
|             |      Y      |
|             |      T      |
|   PYTHON!   |      H      |
|             |      O      |
|             |      N      |
|             |      !      |
|             |             |
-----------------------------
|             |             |
|             |             |
|             |             |
|             |             |
|PYTHON!      |      PYTHON!|
|             |             |
|             |             |
|             |             |
|             |             |
-----------------------------

Here's what I have:

rowBorder = '-' * 29
col = '|'
space = ' '
emptyColRow4 = (col + space * 13 + col + space * 13 + col + "\n") * 4
text = 'PYTHON!'
emptyRow = col+space*13+col+space*13+col

print(rowBorder)
print(emptyRow)
for l in text:
    if l != 'H':
        verticalLetter = '{}{}{}'.format(col + space*13 + col + space*6,l,space*6+col)
    else:
        verticalLetter = '{}{:^13}{}{}{}'.format(col,text, col + space*6,l,space*6+col)
    print(verticalLetter)
print(emptyRow)
print(rowBorder)
print(emptyColRow4,end='')
print('{}{:<13}{}{:>13}{}'.format(col,text,col,text,col))
print(emptyColRow4,end='')
print(rowBorder)

Is there some way we could embed the for loop directly into the print statement?


Solution

  • Python supports the concept of format-strings. A format string such as below allows you to store data into a string almost as if it were literal. This is not required to answer your question but it is nice. A list comprehension joined by new-lines would be how I would wrap your loop into a single line. It is my opinion that this does too much in a single line but here is a way you could do it.

    print('\n'.join([f'{col}{text if l == "H" else space:^13}{col}{space*6}{l}{space*6+col}' for l in text]))