Reputation: 113
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, no additional characters are added. For example, if s1 contained "abc" and s2 contained "uvwxyz", then the new string should contain "aubvcw". Assign the new string to the variable s3.
I have tried like this but it keeps giving me an error:
s3 = ""
for i in range(len(s1)):
s3 += s1[i] + s2[i]
join.min(s1,s2)
For example is s1 is "abc"
and s2 is "uvwxyz"
.
s3 should result "aubvcw"
.
Upvotes: 0
Views: 386
Reputation: 4248
I present two solutions. One using the min()
function and one that does not...
min()
In [26]: s3 = ''
Calculate the length of each string and use min()
to capture the shortest length.
In [27]: short = min(len(s1), len(s2))
By using short
in the range()
function, we can limit the number of iterations to the number of characters in the shortest string...
In [28]: for i in range(short):
...: s3 += s1[i] + s2[i]
...:
In [29]: s3
Out[29]: 'aubvcw'
min()
A possible solution that does not use min()
is to take advantage of the zip()
function and the string method join()
.
The zip
function pairs elements, one by one, from each of the inputs AND by default stops creating pairs when it reaches the end of the shortest input).
In [18]: s1 = 'abc'
In [19]: s2 = 'uvwxyz'
In this case, zip()
will produce a sequence of pairs, that look like this:
('a', 'u')
('b', 'v')
('c', 'w')
The inner ''.join()
method below combines each element of each pair with an empty string. This will result in a sequence of digraphs: 'au'
, 'bv'
, 'cw'
.
The outer ''.join()
method then combines each digraph with an empty string.
In [22]: ''.join(''.join(pair) for pair in zip(s1, s2))
Out[22]: 'aubvcw'
Upvotes: 1