Traversing two strings at a time python

前端 未结 4 1139
悲&欢浪女
悲&欢浪女 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:42

    Here's an explanation of why that doesn't work:

    When you write:

    for c, d in s1, s2:
        # ...
    

    It means:

    for c, d in [s1, s2]:
        # ...
    

    Which is the same as:

    for s in [s1, s2]:
        c, d = s
        # ../
    

    When s is Hi, the letters get unpacked into c and d - c == 'H', d == 'i'. When you try to do the same thing with Giy, python cannot unpack it, since there are three letters but only two variables.


    As already mentioned, you want to use zip_longest

提交回复
热议问题