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
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)
How about:
>>> column1 = ["soft","pregnant","tall"]
>>> column2 = ["skin","woman", "man"]
>>> for line in zip(column1, column2):
... print '{:10}{}'.format(*line)
...
soft skin
pregnant woman
tall man
column1 = ["soft","pregnant","tall"]
column2 = ["skin","woman", "man"]
for row in zip(column1, column2):
print "%-9s %s" % row # formatted to a width of 9 with one extra space after
Using Python 3
column1 = ["soft","pregnant","tall"]
column2 = ["skin","woman", "man"]
for line in zip(column1, column2):
print('{:10}{}'.format(*line))
One liner using new style string formatting:
>>> column1 = ["soft", "pregnant", "tall"]
>>> column2 = ["skin", "woman", "man"]
>>> print "\n".join("{0}\t{1}".format(a, b) for a, b in zip(column1, column2))
soft skin
pregnant woman
tall man
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.