[英]How to print out multiples lines of text in a row (one next to the other) in Python
所以如果我举个例子:
print("some text\n
some more text\n
yet some more text")
和:
print("another some text\n
another some more text\n
yet another some more text")
如何不将它们彼此相邻地打印:
print("some text another some text\n
some more text another some more text\n
yet some more text yet another some more text")
我不想做我刚刚向您展示的内容,因为我将使用不同的文本和值生成更多此类列,但是我希望它们之间使用\\n
分隔符并排。
如何在Python中做到这一点?
进行此操作的一种简单方法是遍历像这样的字符串列表:
column_1 = ["some text", "some more text", "yet some more text"]
column_2 = ["another some text", "another some more text", "yet another some more text"]
for i in range(0, len(column_1 )):
print("{}\t{}".format(column_1[i], column_2[i]))
如果两列的长度当然相同。 如果您想使它们更好地对齐,可以对制表符更加狡猾。
string1 = 'this is a\n string with\n line breaks'
string2 = ' beautiful\n some\n end'
stringcombined = ''.join(list(sum(list(zip(string1.split('\n'), ['\t'+i+'\n' for i in string2.split('\n')])), ()))).replace('\n ','\n')
print(stringcombined)
输出:
this is a beautiful
string with some
line breaks end
编辑:
stringcombined = ''.join(list(sum(list(zip([i+'\n' for i in string1.split('\n')], [i+'\n' for i in string2.split('\n')])), ()))).replace('\n ','\n')
输出:
this is a
beautiful
string with
some
line breaks
end
编辑2:
对于第三列,只需将其添加到zip
string3 = '#\n#\n#'
stringcombined = ''.join(list(sum(list(zip([i+'\n' for i in string1.split('\n')], [i+'\n' for i in string2.split('\n')], [i+'\n' for i in string3.split('\n')])), ()))).replace('\n ','\n')
输出:
this is a
beautiful
#
string with
some
#
line breaks
end
#
看一下这个例子:
a = ["some text", 'some more text', 'yet some more text']
b = ["another some text", "another some more text", "yet another some more text"]
c = ["third text 1", "third text 2", "third text 3"]
print('\n'.join(a))
print('\n'.join(b))
# COMBINED MAGIC:
print('\n'.join(map(lambda x: ('{:30}'*len(x)).format(*x).strip(), zip(a, b, c))))
前两个打印与您的打印相同。 至于最后一步:
a
, b
, c
列表中对应元素的元组 format
功能 上次打印调用的输出:
some text another some text third text 1
some more text another some more text third text 2
yet some more text yet another some more text third text 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.