Home > database >  How to make the elements in a python table go to the next line?
How to make the elements in a python table go to the next line?

Time:01-11

I want to make it so that the elements I am entering in my list go to the next like after a certain time . for example: it prints like this-

[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

I want it to print like this-

1,2,3,4,5,6,7,8,9,10
11,12,13,14,15,16,17,18,19,20

0] I have tried using seperate functions and for loops but cant do it.

> code:
>     b=[' 1', ' 2', ' 3', ' 4',' 5',' 6',' 7',' 8',' 9','10',
>        
>        '11', '12', '13', '14','15','16','17','18','19','20',]
>     x=len(b)
>     for i in range(x):
>         if b[i]==b[9]:
>             b[i 1]=b[i] '\n'
>             
>     print(b)

this is what my code outputs:

[' 1', ' 2', ' 3', ' 4', ' 5', ' 6', ' 7', ' 8', ' 9', '10', '10\n', '12', '13', '14', '15', '16', '17', '18', '19', '20']

Any and all help will be appreciated!

CodePudding user response:

You can use pprint.

width (default 80) specifies the desired maximum number of characters per line in the output. If a structure cannot be formatted within the width constraint, a best effort will be made.

compact impacts the way that long sequences (lists, tuples, sets, etc) are formatted. If compact is false (the default) then each item of a sequence will be formatted on a separate line. If compact is true, as many items as will fit within the width will be formatted on each output line.

import pprint
b = ['1', ' 2', ' 3', ' 4',' 5',' 6',' 7',' 8',' 9','10', '11', '12', '13', '14','15','16','17','18','19','20',]
pprint.PrettyPrinter(width=60, compact=True).pprint(b)

# You can also use this
# pprint.pprint(b, width=60, compact=True)

Output:

['1', ' 2', ' 3', ' 4', ' 5', ' 6', ' 7', ' 8', ' 9', '10',
 '11', '12', '13', '14', '15', '16', '17', '18', '19',
 '20']

CodePudding user response:

Check out list slicing which would make your job much easier. Here is the complete solution.

b = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20"]
print(",".join(b[:10])   "\n"   ",".join(b[10:]))

Output:

1,2,3,4,5,6,7,8,9,10
11,12,13,14,15,16,17,18,19,20

CodePudding user response:

Using

  • Print with multiple arguments and specified separator
  • list slicing of the values array

Code

b = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
maxlen = 10
print(*b[:maxlen], sep = ',') # multiple arguments with separator
print(*b[maxlen:], sep = ',')

Output

1,2,3,4,5,6,7,8,9,10
11,12,13,14,15,16,17,18,19,20
  •  Tags:  
  • Related