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

4
在我正在开发的程序中,我需要让三个多行字符串相邻打印,因此每个字符串的第一行在同一行上,第二行在同一行上,以此类推。
输入:
    '''string
    one'''
    '''string
    two'''
    '''string
    three'''

输出:

    string
    one
    string
    two
    string
    three

期望的结果:

     stringstringstring
     one   two   three

请发布一个“预期结果”。 - dot.Py
5个回答

4

为什么不使用非常复杂的一行代码?

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

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

您可以使用Python 3的print函数实现此操作:
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')

这适用于有两行以上的字符串(所有字符串必须具有相同数量的行或将zip更改为itertools.izip_longest


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

输出:

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

我喜欢这个教程,它与我的代码非常接近,但解释得很清楚。+1 - JBernardo

1
s = """
you can

    print this

string
"""

print(s)

抱歉,我可能没有表达清楚。我的问题是,我在列表的不同项目中存储了ASCII艺术,并且我需要将这些项目并排打印出来。 - Hayden Heffernan
哇,那你应该编辑一下你的问题... 你试过使用 .split()''.join() 吗?你的输入是一个包含字符串的 list 吗? - dot.Py

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接