2

I am trying to write a program that asks the user for two strings and creates a new string by merging the two together (take one letter from each string at a time). I am not allowed to use slicing. If the user enters abcdef and xyzw, program should build the string: axbyczdwef

s1 = input("Enter a string: ")
s2 = input("Enter a string: ")
i = 0
print("The new string is: ",end='')
while i < len(s1):
    print(s1[i] + s2[i],end='')
    i += 1

The problem I am having is if one of the strings is longer than the other I get an index error.

2 Answers 2

2

You need to do your while i < min(len(s1), len(s2)), and then make sure to print out the remaining part of the string.

OR

while i < MAX(len(s1), len(s2)) and then only print s1[i] if len(s1) > i and only print s2[i] if len(s2) > i in your loop.

Sign up to request clarification or add additional context in comments.

Comments

1

I think zip_longest in Python 3's itertools gives you the most elegant answer here:

import itertools

s1 = input("Enter a string: ")
s2 = input("Enter a string: ")

print("The new string is: {}".format(
      ''.join(i+j for i,j in itertools.zip_longest(s1, s2, fillvalue=''))))

Here's the docs, with what zip_longest is doing behind the scenes.

2 Comments

Definitely a better answer than mine, though perhaps less inline with the educational goal of the assignment.
Danke Daniel! :) Oops, I left in her original i which was unused, thanks for bumping this for me. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.