Traversing two strings at a time python

前端 未结 4 1177
悲&欢浪女
悲&欢浪女 2021-01-07 08:58

I have two strings and I want to print them one character at a time alternatively. Like say

s1 = \"Hi\"
s2 = \"Giy\"

for c,d in s1,s2:
    print c
    print         


        
4条回答
  •  长情又很酷
    2021-01-07 09:23

    Use zip():

    for c, d in zip(s1, s2):
        print c, d,
    

    Note that this does limit the loop to the shortest of the strings.

    If you need all characters, use itertools.izip_longest() instead:

    from itertools import izip_longest
    
    for c, d in izip_longest(s1, s2, fillvalue=''):
        print c, d,
    

    Your version looped over the tuple (s1, s2), so it would print s1 first, then s2.

提交回复
热议问题