Reputation: 31
Given the strings s1
and s2
, not necessarily of the same length. Create a new string consisting of alternating characters of s1
and s2
(that is, the first character of s1
followed by the first character of s2
, followed by the second character of s1
, followed by the second character of s2
, and so on.
Once the end of either string is reached, the remainder of the longer string is added to the end of the new string. For example, if s1
contained "abc" and s2
contained "uvwxyz", then the new string should contain "aubvcwxyz". Associate the new string with the variable s3
.
My attempt is:
s3 = ''
i = 0
while i < len(s1) and i < len(s2):
s3 += s1[i] + s2[i]
i += 1
if len(s1) > len(s2):
s3 += s1[i:]
elif len(s2) > len(s1):
s3 += s2[i:]
Upvotes: 2
Views: 12473
Reputation: 1
i = 0
s3 = ''
minLen = min(len(s1),len(s2))
while i < minLen:
s3 = s3+ s1[i] + s2[i]
i += 1
if maxLen != minLen:
s3 += s1[minLen:]+s2[minLen:]
Upvotes: -1
Reputation: 1
we can first decide which string is longer then write a for loop for that condition.
s3 = ""
i=0
if len(s1)>len(s2):
for i in range(len(s2)) :
s3 = s3 + s1[i] + s2[i]
i=i+1
s3=s3+s1[i:]
else:
for i in range(len(s1)) :
s3 = s3 + s1[i] + s2[i]
i=i+1
s3=s3+s2[i:]
Upvotes: 0
Reputation: 165
In python3.x, the following code block works, because Python slices return all of elements in range or an empty string if the index values aren't valid for that string:
n = min(len(s1),len(s2))
s3=""
for i in range(0,n):
s3 = s3 + s1[i] + s2[i]
s3 = s3 + s1[n:] + s2[n:]
Upvotes: 0
Reputation: 1674
a = 'abc'
b= 'uxyz'
c=''
t=0
while t<len(a):
c+=a[t]+b[t]
t+=1
c+=b[t:]
print(c)
This should be the bare minimum for you to tweak some more so you learn from this. I suggest adding some conditionals and turning it into a function so it can take so s1 and s2 can be any length and it will still work. That'll be fun~
Upvotes: 0
Reputation: 10951
You can do it using izip_longest
method from itertools module, this way:
import itertools as it
s3 = ''.join(''.join(item) for item in it.izip_longest(s1,s2,fillvalue=''))
DEMONSTRATION:
>>> s1 = 'ABCDEF'
>>> s2 = '123456789'
>>> s3 = ''.join(''.join(item) for item in it.izip_longest(s1,s2,fillvalue=''))
>>>
>>> s3
'A1B2C3D4E5F6789'
EDIT: in avoiding multiple join
:
s3 = ''.join(c for item in it.izip_longest(s1,s2,fillvalue='') for c in item)
Upvotes: 1
Reputation: 51
s1 = "abcdefg"
s2 = "hijk"
s3 = ""
minLen = min(len(s1), len(s2))
for x in range(minLen):
out += s1[x]
out += s2[x]
out += s1[minLen:]
print out
A couple of things to keep in mind. First, you can treat a python string like an array, and you can access the item at given index using brackets. Also, the second to last line makes use of splicing, for more information, see How can I splice a string?
Upvotes: 3