Reputation: 113
Given the strings s1
and s2
that are of the same length, creating a new string consisting of the last character of s1
followed by the last character of s2
, followed by the second to last character of s1
, followed by the second to last character of s2
, and so on (In other words the new string should consist of alternating characters of the reverse of s1
and s2
).
For example, if s1
contained hello
and s2
contained world
, then the new string should contain odlllreohw
. Assign the new string to the variable s3
.
I have done this far:
s3 = ""
for i in range(len(s1)):
s3 = s2.reverse[i] + s1.reverse[i]
Where should I fix it?
Upvotes: 1
Views: 1287
Reputation: 318
This solution will work for python2
str1 = "hello"
str2 = "world"
for i,j in reversed(zip(str1,str2)):
print i,j,
for python3 you should reverse strings individually
for i,j in zip(str1[::-1],str2[::-1]):
Upvotes: 2
Reputation: 6781
Following your code structure, just reverse
the strings and add them one-by-one :
s1=s1[::-1] #reverse string s1
s2=s2[::-1] #reverse string s2
s3 = ""
for i in range(len(s1)):
s3 += s1[i]+s2[i] #add from both strings letter-wise
#driver values
IN : s1="hello"
IN : s2="world"
OUT : 'odlllreohw'
Upvotes: 1
Reputation: 3698
>>> str1 = 'hello'
>>> str2 = 'world'
>>> my_str = ''.join(y for x in zip(str1[::-1], str2[::-1]) for y in x)
>>> my_str
odlllreohw
...you can use reversed()
, as well.
Upvotes: 3