Reputation: 11
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
Upvotes: 1
Views: 184
Reputation: 73470
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
Upvotes: 0
Reputation: 1632
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)))
Upvotes: 1
Reputation: 8010
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.
Upvotes: 2