Reputation:
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.
How can I do that in Python?
Upvotes: 0
Views: 2144
Reputation: 1608
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
listsformat
functionOutput 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
Upvotes: 0
Reputation: 1847
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:
For a third column just add it inside 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
#
Upvotes: 0
Reputation: 1037
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.
Upvotes: 2