![](/img/trans.png)
[英]The best and shortest way to print multiline strings (ascii art) on the same line, even when the height is different in Python
[英]How to print multiline strings on the same line in Python
在我正在开发的程序中,我需要将3个多行字符串彼此相邻打印,因此每个字符串的第一行在同一行上,每个字符串的第二行在同一行上,依此类推。
输入:
'''string
one'''
'''string
two'''
'''string
three'''
输出:
string
one
string
two
string
three
所需结果:
stringstringstring
one two three
为什么不是一个非常复杂的衬垫?
假设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
)
不是单线的...
# 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))
输出:
_____ _____ _____
/ /\ / /\ / /\
/____/ \/____/ \/____/ \
\ \ /\ \ /\ \ /
\____\/ \____\/ \____\/
s = """
you can
print this
string
"""
print(s)
这个怎么样:
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),
这种方法离我更近。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.