How do I print two strings vertically side by side

时间:2019-04-08 12:50:55

标签: python python-3.x

I have code where I want print two string vertically side by side like

hp
ea
lu
ll
o

but I am unable to print them how do i modify my given code my code is

s1='hello'
s2='paul'
i=0
while i<len(s1) and i<len(s2):
   print(s1[i],s2[i])
   i+=1

4 个答案:

答案 0 :(得分:6)

this is a variant using itertools.zip_longest:

from itertools import zip_longest

s1='hello'
s2='paul'

for a, b in zip_longest(s1, s2, fillvalue=' '):
    print(a, b)

答案 1 :(得分:3)

To get your current code to work, you should use the or operator in your condition instead of and, and use a conditional operator to default your list values to a space if the index is not less than the length of the list:

s1 = 'hello'
s2 = 'paul'
i = 0
while i < len(s1) or i < len(s2):
    print(s1[i] if i < len(s1) else ' ', s2[i] if i < len(s2) else ' ')
    i += 1

答案 2 :(得分:1)

you can use zip_longest here:

from itertools import zip_longest
s1 = 'hello'
    s2 = 'paul'
    for c1, c2 in zip_longest(s1, s2, fillvalue=' '):
        print(c1, c2)

if you are not familiar with that, don't worry, you can use your version, I have fixed it, just continue the while loop separately:

s1 = 'hello'
s2 = 'paul'
i = 0
while i < len(s1) and i < len(s2):
    print(s1[i], s2[i])
    i += 1

while i < len(s1):
    print(s1[i], ' ')
    i += 1

while i < len(s2):
    print(' ', s2[i])
    i += 1

output:

h p
e a
l u
l l
o 

Hope that helps you, and comment if you have further questions. : )

答案 3 :(得分:1)

I like the zip method suggested by @Netwave but you must have strings of the same size for it to work.

Here a patched version:

s1 = 'Hello'
s2 = 'Paul'
#make strings equal in length
if len(s1) != len(s2):
    while len(s1) < len(s2):
        s1 += ' '
    while len(s2) < len(s1):
        s2 += ' '

txt = "\n".join(f"{x}{y}" for x, y in zip(s1, s2))
print(txt)

Output:

HP
ea
lu
ll
o