Merge two strings with alternate chars as output

后端 未结 5 1290
悲哀的现实
悲哀的现实 2021-01-17 01:53

I got the task to alternately combine the letters of two strings with the same length.

For example:

Inputstring 1: \"acegi\"

Inputstring 2: \"bdfhj\         


        
5条回答
  •  太阳男子
    2021-01-17 02:04

    You have several problems in your code. The one that is the most important is your naming problem. Give meaningful names to your variables.

    Now, to the logic. You need to iterate through your strings at the same time, or use an index on both at the same time, and not one after the other.

    You could do as such, for a more pythonic way of doing this.

    first = input("Your first string.")
    second = input("Your second string.")
    
    if len(first) != len(second):
        print 'Bad length for the inputs.'
    else:
        newString = ""
        for s1, s2 in zip(first, second):
            newString += s1 + s2
        print newString
    

提交回复
热议问题