Home > front end >  how to print a string a certain number of times on a line then move to a new line
how to print a string a certain number of times on a line then move to a new line

Time:11-26

I have the list ['a','b','c','d','e','f','g']. I want to print it a certain way like this:

a b c 
d e f
g

this is what I've tried:

result = ''
for i in range(len(example)):
    result  = example[i]   ' '
    if len(result) == 3:
        print('\n')
print(result)

but with this I continue to get one single line

CodePudding user response:

Iterate over a range of indices and step by 3, creating slices of three elements at a time.

>>> a = ['a','b','c','d','e','f','g']
>>> for i in range(0, len(a), 3):
...   print(a[i:i 3])
... 
['a', 'b', 'c']
['d', 'e', 'f']
['g']
>>> 

To format the data, you could either join the slice with ' ' or expand it out and use the sep argument to print.

>>> for i in range(0, len(a), 3):
...   print(' '.join(a[i:i 3]))
... 
a b c
d e f
g
>>> for i in range(0, len(a), 3):
...   print(*a[i:i 3], sep=' ', end='\n')
... 
a b c
d e f
g
>>> 

CodePudding user response:

The problem with the example code above is that len(result) will never be 3. result is always increased by a character plus a space, so its length will always be a multiple of 2. While you could adjust the check value to compensate, it will break if the list elements are ever more than 1 character. Additionally, you don't need to explicitly print a "\n" in Python, as any print statement will automatically end with a new line character unless you pass a parameter to not do that.

The following takes a different approach and will work for any list, printing 3 elements, separated by spaces, and then printing a new line after every third element. The end parameter of print is what should be added after the other arguments are printed. By default it is "\n", so here I use a space instead. Once the index counter exceeds the list size, we break out of the loop.

i = 0
while True:
    print(example[i], end=' ')
    i  = 1
    if i >= len(example):
        break
    if i % 3 == 0:
        print()  # new line

CodePudding user response:

Using enumerate

example = ['a','b','c','d','e','f','g'] 
max_rows = 3
result = ""
for index, element in enumerate(example):
    if (index % max_rows) == 0:
        result  = "\n"
    result  = element

print(result)

  • Related