Traversing two strings at a time python

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

    you need to use itertools.izip_longest():

    In [7]: from itertools import izip_longest
    
    In [8]: s1="Hi"
    
    In [9]: s2="Giy"
    
    In [10]: "".join("".join(x) for x in izip_longest(s1,s2,fillvalue=""))
    Out[10]: 'HGiiy'
    

    or using a simple for loop:

    s1="Hi"
    s2="Giy"
    ans=""
    for i in range(min(len(s1),len(s2))):
        ans+=s1[i]+s2[i]
    ans += s1[i+1:]+s2[i+1:]    
    print ans                 #prints HGiiy
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-07 09:29

    Use this function,

       def  mergeStrings(a, b):
            s = ''
            count = 0
            for i in range(min(len(a),len(b))):
                s+=a[i]
                s+=b[i]
                count+=1
            s+= a[count:] if len(a) > len(b) else b[count:]
            return s
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题