2017-04-12 96 views
1

在我正在處理的程序中,我需要將3個多行字符串打印出來,因此每個字符串的第一行位於同一行,每個字符串的第二行是在同一條線上,等等如何在Python中的同一行上打印多行字符串

輸入:

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

輸出:

string 
    one 
    string 
    two 
    string 
    three 

期望的結果:

 stringstringstring 
    one two three 
+0

請,張貼'預計result' –

回答

1
s = """ 
you can 

    print this 

string 
""" 

print(s) 
+0

對不起,我可能不是足夠清晰。我的問題是,我將ascii藝術存儲在列表中的不同項目中,並且我需要將這些項目打印在一起。 –

+0

哇,你應該編輯你的問題,然後......你試過'.split()'和'''.join()'?你的輸入是一個帶有字符串的「列表」嗎? –

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

爲什麼不是一個非常令人費解的一個班輪?

假設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線串(所有字符串必須具有相同的線數或更改zipitertools.izip_longest

1

不是單線...

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

輸出:

_____ _____ _____ 
/ /\/ /\/ /\ 
/____/ \/____/ \/____/ \ 
\ \ /\ \ /\ \/
\____\/ \____\/ \____\/ 
+0

我喜歡這是如何接近我的代碼,但很好解釋。 +1 – JBernardo