[英]How to print out multiples lines of text in a row (one next to the other) in Python
So if I got for example: 所以如果我举个例子:
print("some text\n
some more text\n
yet some more text")
and: 和:
print("another some text\n
another some more text\n
yet another some more text")
How can print them next to each other without doing this: 如何不将它们彼此相邻地打印:
print("some text another some text\n
some more text another some more text\n
yet some more text yet another some more text")
I don't want to do what I just showed you, because I'll be generating more of this columns with different text and values, but I want them next to each other with the \\n
breaks. 我不想做我刚刚向您展示的内容,因为我将使用不同的文本和值生成更多此类列,但是我希望它们之间使用
\\n
分隔符并排。
How can I do that in Python? 如何在Python中做到这一点?
A simple way to go on about this is to loop over the lists of strings like so : 进行此操作的一种简单方法是遍历像这样的字符串列表:
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]))
If the length of both columns is the same of course. 如果两列的长度当然相同。 You could be more crafty with the tabbing if you want to align them better.
如果您想使它们更好地对齐,可以对制表符更加狡猾。
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)
Output: 输出:
this is a beautiful
string with some
line breaks end
Edit: 编辑:
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')
Output: 输出:
this is a
beautiful
string with
some
line breaks
end
Edit2: 编辑2:
For a third column just add it inside zip
对于第三列,只需将其添加到
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')
Output: 输出:
this is a
beautiful
#
string with
some
#
line breaks
end
#
Take a look into this example: 看一下这个例子:
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))))
First two prints are equal to yours. 前两个打印与您的打印相同。 As for the last one step-by-step:
至于最后一步:
a
, b
, c
lists a
, b
, c
列表中对应元素的元组 format
function format
功能 Output from the last print call: 上次打印调用的输出:
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.