2

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

  • 3
    The output works line by line, so try with a single for loop :) – Nasta Nov 27 '20 at 13:38
  • 1
    Try using the `end` parameter of `print` function – atin Nov 27 '20 at 13:40
  • Duplicates: [How do I print two strings vertically side by side](https://stackoverflow.com/q/55573915/7851470), [vertical print string in python 3](https://stackoverflow.com/q/32872306/7851470). – Georgy Dec 02 '20 at 15:14

5 Answers5

3

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
* * * 
* *   
  *   
  *   
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47
2

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.

Szabolcs
  • 3,990
  • 18
  • 38
2

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)
Dion Saputra
  • 322
  • 2
  • 15
2

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
* * * 
* *   
  *   
  *   
yakobyd
  • 572
  • 4
  • 12
1

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