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
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
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.
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
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