Hayden Heffernan
Hayden Heffernan

Reputation: 41

How to print multiline strings on the same line in Python

In the program I'm working on I need to have 3 multiline strings print out next to each other, so the first line of each string is on the same line, the second line of each string is on the same line, etc.

Input:

'''string
one''',
'''string
two''',
'''string
three'''

Output:

string
one
string
two
string
three

Desired result:

stringstringstring
one   two   three

Upvotes: 4

Views: 3676

Answers (5)

zipa
zipa

Reputation: 27889

How about this (for Python 2):

strings = [x.split() for x in [a, b, c]]
just = max([len(x[0]) for x in strings])
for string in strings:
    print string[0].ljust(just),
print
for string in strings:
    print string[1].ljust(just),

Upvotes: 0

vield
vield

Reputation: 306

strings = ['string\none', 'string\ntwo', 'string\nthree']

# Split each multiline string by newline
strings_by_column = [s.split('\n') for s in strings]

# Group the split strings by line
strings_by_line = zip(*strings_by_column)

# Work out how much space we will need for the longest line of
# each multiline string
max_length_by_column = [
    max(len(s) for s in col_strings)
    for col_strings in strings_by_column
]

for parts in strings_by_line:
    # Pad strings in each column so they are the same length
    padded_strings = [p.ljust(n) for p, n in zip(parts, max_length_by_column)]
    print(''.join(padded_strings))

Output:

stringstringstring
one   two   three 

Note that the strings have to have the same number of lines for this to work.

Upvotes: 4

Raymond Reddington
Raymond Reddington

Reputation: 1837

This approach is closer to me.

first_str = '''string
one'''
second_str = '''  string
  two  '''
third_str = '''string
three'''

str_arr = [first_str, second_str, third_str]
parts = [s.split('\n') for s in str_arr]
f_list = [""] * len(parts[0])
for p in parts:
    for j in range(len(p)):
        current = p[j] if p[j] != "" else "   "
        f_list[j] = f_list[j] + current

print('\n'.join(f_list))

Output:

string  stringstring
one  two  three

Upvotes: -1

JBernardo
JBernardo

Reputation: 33407

Why not a very convoluted one liner?

Assuming strings is your list of multiline strings:

strings = ['string\none', 'string\ntwo', 'string\nthree']

You can do this with Python 3s print function:

print(*[''.join(x) for x in zip(*[[x.ljust(len(max(s.split('\n'), key=len))) for x in s.split('\n')] for s in strings])], sep='\n')

This works for strings with more than 2 lines (all strings must have the same number of lines or change zip to itertools.izip_longest)

Upvotes: 3

dot.Py
dot.Py

Reputation: 5157

s = """
you can

    print this

string
"""

print(s)

Upvotes: 1

Related Questions