Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop print through two lists to get two columns with fixed(custom set) space between the first letter of each element of each list

Suppose I have these two lists:

column1 = ["soft","pregnant","tall"]
column2 = ["skin","woman", "man"]

How do I loop print through these two lists while using a custom, fixed space(say 10, as in example) starting from the first letter of each element of the first list up to the first letter of each element of the second list?

Example output of a set spacing of 10:

soft      skin
pregnant  woman 
tall      man
like image 464
Bentley4 Avatar asked Aug 23 '12 12:08

Bentley4


People also ask

How do you print two lists in Python?

You can use the zip() function to join lists together. The zip() function will iterate tuples with the corresponding elements from each of the lists, which you can then format as Michael Butscher suggested in the comments. Finally, just join() them together with newlines and you have the string you want.


1 Answers

Easily done with the string formatting,

column1 = ["soft","pregnant","tall"]
column2 = ["skin","woman", "man"]

for c1, c2 in zip(column1, column2):
    print "%-9s %s" % (c1, c2)

Or you can use str.ljust, which is tidier if you want to have the padding be based on a variable:

padding = 9
for c1, c2 in zip(column1, column2):
    print "%s %s" % (c1.ljust(padding), c2)

(note: padding is 9 instead of 10 because of the hard-coded space between the words)

like image 128
dbr Avatar answered Oct 21 '22 20:10

dbr