简体   繁体   中英

format lists in python 3.9.1

Iam trying to format 2 lists in python

l1 = ["Marc", "Peter", "Loise", "Walter"]
l2 = ["a2", "3w3", "3e5", "320"]

list1 = "  ".join(l1)
list2 = "  ".join(l2)

print(list1)
print(list2)

Output

Marc  Peter  Loise  Walter
a2  3w3  3e5  320

Iam looking for a way to count the letters in every string to format l2 to look like this

Marc  Peter  Loise  Walter
a2    3w3    3e5    320

thanks in advance

There are 2 basic ways to approach this, one is using tabs:

"\t".join(l1)

This will work if the elements in both lists are within 4 characters of eachother. If you have to deal with bigger differences use:

"".join("{:<10}".format(i) for i in l1)

This will pad the string to 10 characters. Replace 10 with any number of characters you would like.

You are looking for string formatting. In your case, you want to add enough spaces that the strings appear aligned. The easiest way for your example would be to use tabs: '\t'.join(l)

Otherwise you'll need to work with ljust and it gets more complex:

list1 = ''
list2 = ''
for a, b in zip (l1, l2):
    list1 += '  ' + a.ljust(max(len(a),len(b)))
    list2 += '  ' + b.ljust(max(len(a),len(b)))

Get the required widthes and justify each column:

w = [max(map(len, x)) for x in zip(l1, l2)]

line1 = " ".join(x.ljust(y) for x, y in zip(l1, w))
line2 = " ".join(x.ljust(y) for x, y in zip(l2, w))

Marc Peter Loise Walter
a2   3w3   3e5   320 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM