Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore multiple new lines in python [duplicate]

Tags:

python

This is the code I have written

a = "*" * 2 
b = "*" * 4
c = "*" * 1

print("a","b","c")

for each in a:
  print('{:>5}'.format(each))

for each in b:
  print('{:>10}'.format(each))

for each in c:
  print('{:>15}'.format(each))

The output I get is something like this

a  b  c
*
*
   *
   *
   *
   *
       *

However the output I want to get is something like this

a  b  c
*  *  *
*  *
   *
   *

Any idea on how I can get the output I want? Appreciate any help possible


2 Answers

Use one loop to iterate over a,b,c to be able to print line by line:

a = "*" * 2
b = "*" * 4
c = "*" * 1

items = [list(x) for x in (a, b, c)]
print("a", "b", "c")

# repeat until a,b,c are empty.
while any(items):
    for item in items:
        print(item.pop() if item else ' ', end=' ')
    print("")

Out:

a b c
* * * 
* *   
  *   
  *   
like image 155
Maurice Meyer Avatar answered Aug 01 '26 18:08

Maurice Meyer


I think you should combine 'a, b, c' in one loop:

a = "*" * 2 
b = "*" * 4
c = "*" * 1

print("a","b","c")

for line in range(max(len(a), len(b), len(c))):
    row = ""
    row += "* " if line < len(a) else "  "
    row += "* " if line < len(b) else "  "
    row += "* " if line < len(c) else "  "
    print(row)
like image 25
Dion Saputra Avatar answered Aug 01 '26 18:08

Dion Saputra