Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print multiline strings on the same line in Python

Tags:

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
like image 838
Hayden Heffernan Avatar asked Mar 09 '23 09:03

Hayden Heffernan


1 Answers

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)

like image 117
JBernardo Avatar answered Apr 28 '23 03:04

JBernardo