简体   繁体   中英

A program to print the alternate letters of a word in one word. Like abc and ABC aAbBcC

Write a program that asks the user to enter two strings of the same length. The program should then check to see if the strings are of the same length. If they are not, the program should print an appropriate message and exit. If they are of the same length, the program should print the alternate characters of the two strings. For example, if the user enters abcde and ABCDE the program should print out AaBbCcDdEe.

I have tried this but it does not work

t1 = input('Enter a string: ')
t2  = input('Enter another string: ')
run = True
while run:
    if (len(t1)!=len(t2)):
        run = False
elif (len(t1)==len(t2)):
    for i in range(len(t1),len(t2)):
        if (i%2 ==0):
            t1[i]+=t2[i]
            print(t1)

Something like this, it is possible to be more clever with building the string, but this maybe is the easiest to understand.

a = input("string a:")
b = input("string b:")

s= ""
if len(a) != len(b):
    print("Not same length!")
else:
    for i,k in zip(a,b):
        s += i+k
    print(s)

Here without rebuilding the string each time:

s= []
if len(a) != len(b):
    print("Not same length!")
else:
    for i,k in zip(a,b):
        s.append(i)
        s.append(k)
    print("".join(s))

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