简体   繁体   中英

Merge two strings with alternate chars as output

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

For example:

Inputstring 1: "acegi"

Inputstring 2: "bdfhj"

Outputstring: "abcdefghij"

And I got the following Problem when I run my code.

Traceback (most recent call last):  
  File "...", line 14, in <module>
    x =x+f
TypeError: must be str, not int

I think every relevant variable is a String .

s=str(input("Input first String:"))
v=str(input("Input second String:"))
x=""
c=1
z=""
f=""
laenge=len(s)
lenge=len(v)

for f in range(laenge):

    if f in range(c,c+1):
        x =x+f
for z in range(lenge):

    if z in range(c,c+1):
        x=x+z
c=c+1

print(x)

One of the first things you should learn when programming is to use meaningful variable names, not cryptic, 1-letter names.

Your code is not alternating between the two input strings. You're looping through the first string, then looping through the second string, and never repeating.

I'm not sure what the point of the c variable is. You set it to 1 at the beginning of the script, then add 1 to it later, but then the script ends. Was there supposed to be another loop around all that code?

The loop that checks if f is in range(c, c+1) could just be f = c , there's no point to looping.

The error is coming from

x = x + f

because x is a string and f is an int . I suspect you wanted to do x = x + s[f] .

The whole thing can be simplified greatly.

string1 = input("Enter string 1: ")
len1 = len(string1)
string2 = input("enter string 2: ")
len2 = len(string2)
if len1 != len2:
    print("Inputs must be the same length")
else:
    result = ""
    for i in range(len1):
        result += string1[i]
        result += string2[i]
    print(result)

You can do it in one line using zip and join .

out1 = ''.join(''.join(f for f in tup) for tup in zip(inp1, inp2))

or the more functional-style:

out1 = ''.join(map(''.join, zip(inp1, inp2)))  # kudos @Coldspeed

which both print

abcdefghij

Braking the code down:

  • zip()

     pairs = list(zip(inp1, inp2)) print(pairs ) # [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h'), ('i', 'j')] 
  • .join()

     temp = [] for sub in pairs: temp.append(''.join(sub)) print(temp) # ['ab', 'cd', 'ef', 'gh', 'ij'] 
  • .join() again

     out1 = ''.join(temp) print(out1) # abcdefghij 

Finally, and for your entertainment and learning only, two additional, more old-school approaches:

out1 = ''
for i in range(len(inp1)):
    out1 += inp1[i] + inp2[i]

and

out1 = ''
for i, c in enumerate(inp1):
    out1 += c + inp2[i]

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

One can simply use map with join to get desired result:

"".join(map(lambda x,y: x+y, astr, bstr))

zip in not needed here since 2 strings/lists can be provided to map which has a lambda function that takes 2 arguments. Also, + symbol works to concatenate 2 strings here.

Get a and b with input or however you want. No need to copy that. The point is the code.

a = 'acegi'
b = 'bdfhj'

c = ''
for i in range(len(a)):
    c += a[i] + b[i]

print(c)

Result is:

abcdefghij

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM