Ignore multiple new lines in python

Viewed 136

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

5 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
* * * 
* *   
  *   
  *   

You can try this:

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

texts = [a, b, c]
rows = max(len(text) for text in texts)

print(f"a b c")
for i in range(rows):
    cell_a = a[i] if len(a) > i else " "
    cell_b = b[i] if len(b) > i else " "
    cell_c = c[i] if len(c) > i else " "

    print(f"{cell_a} {cell_b} {cell_c}")

You can apply more formatting for the prints, but it should already print the contents the way you'd like.

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)

I would suggest a different algorithmic approach. For each name ('a', 'b', 'c') calculate whether it requires a '*' in the current row you are printing. A generic function for your task:

def print_sym(names, reps, symbol):
    print(*names)
    for i in range(max(reps)):  # iterate over output rows
        row_str = ""
        for rep in reps:  # iterate over output columns
            row_str += symbol if i < rep else " "
            row_str += " "
        print(row_str)

print_sym(['a', 'b', 'c'], [2, 4, 1], '*') 
a b c
* * * 
* *   
  *   
  *   

Try this one:

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

print("a","b","c")
max_length=len(max(a,b,c))

a+=" "*(max_length-len(a))
b+=" "*(max_length-len(b))
c+=" "*(max_length-len(c))

for i in range(0,max_length):
    print(a[i],b[i],c[i])

output:

a b c
* * *
* *  
  *  
  *
Related