Home > OS >  Python left justify text in second column beginning 3 spaces after the first column
Python left justify text in second column beginning 3 spaces after the first column

Time:10-17

In Python, I have a list of lists like this:

vote_count = [('Matthew', 5), ('Harry', 8)]

and I want to print the list such that the second column of numbers is left justified and starts 3 spaces after the longest string in the first column like this:

Matthew   5
Harry     8

Currently my code does print the array in two left justified columns, but not to the desired specifications. How should I change my print statement to do this?

vote_count = [('Matthew', 5), ('Harry', 88)]
for i in vote_count:
            print("%-10s" "%i" % (i[0], i[1]))

CodePudding user response:

Try the following, which uses a generator comprehension to determine the longest length first and then print the output accordingly using f-string.

vote_count = [('Matthew', 5), ('Harry', 8)]

longest = max(len(name) for name, _ in vote_count)

for name, cnt in vote_count:
    print(f'{name:{longest}}   {cnt}')

# Matthew   5
# Harry     8

CodePudding user response:

vote_count = [('Matthew', 5), ('MatthewMatthewHarryHarry', 20), ('Harry', 88)]
vote_count_new = []
maxlen = 0
space_dist = 3

maxlen = max([(len(i[0]) len(str(i[1]))) for i in vote_count])
for i in vote_count:
    vote_count_new.append((i[0]   ' ' * ((maxlen - len(i[0]) - len(str(i[1])))   (space_dist-1)), i[1]))
for i in vote_count_new:
    print(i[0], i[1])


SCENARIO 1 Output:
vote_count = [('Matthew', 5), ('MatthewMatthewHarryHarry', 20), ('Harry', 88)]

Matthew                     5
MatthewMatthewHarryHarry   20
Harry                      88

SCENARIO 2 Output:
vote_count = [('Matthew', 5), ('MatthewMatthewHarryHarry', 20), ('Harry', 88), ('MatthewMatthewHarryHarry', 123456789)]

Matthew                            5
MatthewMatthewHarryHarry          20
Harry                             88
MatthewMatthewHarryHarry   123456789
  • Related