假设我有这两个列表:
column1 = ["soft","pregnant","tall"]
column2 = ["skin","woman", "man"]
如何在使用自定义的固定空间(例如 10,如示例)从第一个列表的每个元素的第一个字母开始到第二个列表的每个元素的第一个字母的同时循环打印这两个列表?
设置间距为 10 的示例输出:
soft skin
pregnant woman
tall man
假设我有这两个列表:
column1 = ["soft","pregnant","tall"]
column2 = ["skin","woman", "man"]
如何在使用自定义的固定空间(例如 10,如示例)从第一个列表的每个元素的第一个字母开始到第二个列表的每个元素的第一个字母的同时循环打印这两个列表?
设置间距为 10 的示例输出:
soft skin
pregnant woman
tall man
轻松完成字符串格式化,
column1 = ["soft","pregnant","tall"]
column2 = ["skin","woman", "man"]
for c1, c2 in zip(column1, column2):
print "%-9s %s" % (c1, c2)
或者你可以使用str.ljust
,如果你想让填充基于一个变量,它会更整洁:
padding = 9
for c1, c2 in zip(column1, column2):
print "%s %s" % (c1.ljust(padding), c2)
(注意:填充9
不是10
因为单词之间的硬编码空格)
怎么样:
>>> 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
使用 Python 3
column1 = ["soft","pregnant","tall"]
column2 = ["skin","woman", "man"]
for line in zip(column1, column2):
print('{:10}{}'.format(*line))
使用新样式字符串格式的一个班轮:
>>> 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