Home > Software design >  how to print in new column if the nth character is reached in python?
how to print in new column if the nth character is reached in python?

Time:02-20

I need to print in new column if the nth character is reached But i didnt got output

Input:

5
['c', 'o', 'd', 'e', 'f', 'f', 'i', 'l', 'r', 'o', 'e'

output needed:

c f e
o i
d l
e r
f o

my code:

n=5

l= ['c', 'o', 'd', 'e', 'f', 'f', 'i', 'l', 'r', 'o', 'e']
for i in range(0,len(l)):
  print(l[i])
  if i%n==0 and i!=0:
    print('\r')

output got:

c
o
d
e
f
f

i
l
r
o
e

What mistake i made??

CodePudding user response:

You can't go back and print to a line you've already printed. But you can append to a list you've already created. This means you need to save data into a structure first, then print.

So, you need to find a way to loop through the data once and collect the rows into groups so at the end you can loop through them and print. There's a lot of ways to do this. Here's one that uses some of the ideas you already have:

n = 5
l = ['c', 'o', 'd', 'e', 'f', 'f', 'i', 'l', 'r', 'o', 'e']

rows = []
for i, c in enumerate(l):
    if i % n >= len(rows): # if row doesn't exist
        rows.append([])    # make a new one 
    rows[i%n].append(c)    # then append

# now that it's restructured into rows, print
for row in rows:
    print(" ".join(row))

This should print:

c f e
o i
d l
e r
f o

CodePudding user response:

What you want in the form of a function:

def custom_print(column_length, array_to_print):
    chunked_array = [list(array_to_print[i:i column_length]) for i in range(len(array_to_print))[::column_length]]
    for i in range(column_length):
        to_print = []
        for chunk in chunked_array:
            try:
                to_print.append(chunk[i])
            except:
                to_print.append('')
        print(' '.join(to_print))

output:

custom_print(5, ['c', 'o', 'd', 'e', 'f', 'f', 'i', 'l', 'r', 'o', 'e'])
c f e
o i 
d l 
e r 
f o 

CodePudding user response:

You can do this by using a list and storing rows in it like below

grid=[]
n=5
l= ['c', 'o', 'd', 'e', 'f', 'f', 'i', 'l', 'r', 'o', 'e']
for i in range(0,len(l)):
    if i//n==0:
        grid.append(l[i])
    else:
        grid[i%n]=grid[i%n] l[i] 
for row in grid:
    print(row)

CodePudding user response:

A one-line solution based on list comprehension and slicing. It takes the nth characters from the string with the initial offsets on 0,1,...,n-1.

print("\n".join([" ".join(l[i::n]) for i in range(n)]))
#c f e
#o i
#d l
#e r
#f o

CodePudding user response:

Each call to print() must output all the letters to show on the line. Printing cannot move backward:

n = 5
a = ['c', 'o', 'd', 'e', 'f', 'f', 'i', 'l', 'r', 'o', 'e']

for i in range(n):
    print(*a[i::n])

c f e
o i
d l
e r
f o
  • Related