Alternating elements of a string in python

I have to write a program that input something as a string and print this by alternating each element with next element position. Suppose, i take a string is Corona then output should be oCoran.
Without input i made it like that,

name = "Corona"
number1 = name[1],name[0],name[3],name[2],name[5],name[4]
number2 = "".join(number1)
print(number2)

But if i input something then how can i change this?Still thinking…

name = str(input())
name0 = len(name)
for i in range(name0):
    number1 = name[1],name[0],name[3],name[2],name[5],name[4]
number2 = "".join(number1)
print(number2)

I fail to solve this and feeling so depressed. :neutral_face:
Cause,i’m trying to learn python by a book and i already finished string chapter.But in exercise section i can’t find the way to solve this string related problem. :pleading_face:

Can you please try to figure out this problem solution and tell me a best resource or learning plan to learn python according to your own experience?

How far did you get with the solution? On what are you stuck?

Without input i made it like that,

name = "Corona"
number1 = name[1],name[0],name[3],name[2],name[5],name[4]
number2 = "".join(number1)
print(number2)

But if i input something then how can i change this?Still thinking…

name = str(input())
name0 = len(name)
for i in range(name0):
    number1 = name[1],name[0],name[3],name[2],name[5],name[4]
number2 = "".join(number1)
print(number2)

What data type is this? Do you want a tuple?
What do you expect this to do?

I’m sorry i know it’s wrong.But i’m trying to fix this :neutral_face:
What’s my problem can u please help me? I don’t even know what it tuple yet :frowning:

What should happen with an input of an odd length string?
If name = "Steve", what would the output be, if every letter switches with its neighbour?

you can try the code bellow .hope it will help.

inp=input("enter a string = ")
name = str(inp)
nam = []
for i in range(len(name)):
    if(i%2==0):
        nam.append(name[i+1])
    else:
        nam.append(name[i-1])
   
number2 = "".join(nam)
print(number2)
1 Like

if string is odd length then last element will be unchangeable.
Input: Steve
output: tSvee

try this code it will work for all steve and corona:

inp=input("enter a string = ")
name = str(inp)
nam = []
for i in range(len(name)):
    if(len(name)%2==0):
        if(i%2==0):
            nam.append(name[i+1])
        else:
            nam.append(name[i-1])
    else:
        if(i%2==0 and not i==len(name)-1):
            nam.append(name[i+1])
        elif(i==len(name)-1):
            nam.append(name[i])
        else:
            nam.append(name[i-1])        
   
number2 = "".join(nam)
print(number2)
1 Like

Yes ,Exactly.Thank you so much, FatmaNagori :heart: