Evan Weissburg
Evan Weissburg

Reputation: 1594

What's the cleanest way to print an equally-spaced list in python?

Please close if this is a duplicate, but this answer does not answer my question as I would like to print a list, not elements from a list.

For example, the below does not work:

mylist = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
print(%3s % mylist)

Desired output:

[  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15]

Basically, if all items in the list are n digits or less, equal spacing would give each item n+1 spots in the printout. Like setw in c++. Assume n is known.

If I have missed a similar SO question, feel free to vote to close.

Upvotes: 1

Views: 5867

Answers (4)

Shay Lempert
Shay Lempert

Reputation: 301

I think this is the best yet, as it allows you to manipulate list as you wish. even numerically.

mylist = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
print(*map(lambda x: str(x)+" ",a))

Upvotes: 0

Richie Bendall
Richie Bendall

Reputation: 9222

If none of the other answers work, try this code:

    output = ''
    space = ''
    output += str(list[0])
    for spacecount in range(spacing):
        space += spacecharacter
    for listnum in range(1, len(list)):
        output += space
        output += str(list[listnum])
    print(output)

Upvotes: 1

Hatshepsut
Hatshepsut

Reputation: 6662

items=range(10)
''.join(f'{x:3}' for x in items)
'  0  1  2  3  4  5  6  7  8  9'

Upvotes: 3

NaN
NaN

Reputation: 2332

You can exploit formatting as in the example below. If you really need the square braces then you will have to fiddle a bit

lst = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

frmt = "{:>3}"*len(lst)

print(frmt.format(*lst))
  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15

Upvotes: 3

Related Questions