如何在Python中的同一行上打印多行字符串

时间:2017-04-12 14:13:18

标签: python

在我正在编写的程序中,我需要将3个多行字符串打印在一起,所以每个字符串的第一行在同一行,每个字符串的第二行在同一行上线等等。

输入:

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

输出:

    string
    one
    string
    two
    string
    three

期望的结果:

     stringstringstring
     one   two   three

5 个答案:

答案 0 :(得分:3)

为什么不是一个非常复杂的一个班轮?

假设strings是多行字符串列表:

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

您可以使用Python 3s打印功能执行此操作:

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')

适用于超过2行的字符串(所有字符串必须具有相同的行数或将zip更改为itertools.izip_longest

答案 1 :(得分:3)

不是单行......

# Initialise some ASCII art
# For this example, the strings have to have the same number of
# lines.
strings = [
'''
  _____
 /    /\\
/____/  \\
\\    \  /
 \\____\/
'''
] * 3

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

# Group the split strings by line
# In this example, all strings are the same, so for each line we
# will have three copies of the same string.
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 = [
        parts[i].ljust(max_length_by_column[i])
        for i in range(len(parts))
    ]
    print(''.join(padded_strings))

输出:

  _____    _____    _____  
 /    /\  /    /\  /    /\ 
/____/  \/____/  \/____/  \
\    \  /\    \  /\    \  /
 \____\/  \____\/  \____\/ 

答案 2 :(得分:1)

s = """
you can

    print this

string
"""

print(s)

答案 3 :(得分:0)

这个怎么样:

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),

答案 4 :(得分:0)

这种方法离我更近。

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))

输出:

string  stringstring
one  two  three