Home > database >  Swapping the positions of adjacent characters in a string using indexing and loops in Python
Swapping the positions of adjacent characters in a string using indexing and loops in Python

Time:08-30

Using just indexing and loops, how do you swap the positions of adjacent characters in a string, while making an exception for spaces?

I/P: HELLO WORLD

O/P: EHLLO OWLRD

This is the code I wrote:

s1=''
for j in range(0,len(s)-1,2):
   if(skip==1):
                    print()
                    skip=0
   elif(s[j].isspace()==False and s[j 1].isspace()==False):
                    s1=s1 s[j 1] s[j]
   elif(s[j].isspace()==False and s[j 1].isspace()==True):
                    s1=s1 s[j] " "
   elif(s[j].isspace()==True and s[j 1].isspace()==False and s[j 2].isspace()==False):
                    s1=s1 " " s[j 2] s[j 1]
                    skip=1
   elif(s[j].isspace()==True and s[j 1].isspace()==False and s[j 2].isspace()==True):
                    s1=s1 " " s[j 1]
print("new string is",s1)

What exactly am I doing wrong here?

CodePudding user response:

inp = "HELLO WORLD"
expected = "EHLLO OWLRD"

for i in range(0, len(inp), 2):  # iterate in steps of two
    # check to make sure that we are not at end of string and charaters are not spaces
    if i 1 < len(inp) and inp[i] != " " and inp[i 1] != " ":
        # now do the string replacing
        temp1 = inp[i]
        temp2 = inp[i   1]
        
        inp = inp[:i]   temp2   temp1   inp[i 2:]

# output to indicate the new string is what we expect        
print(inp)
print(expected)
print(inp == expected)

CodePudding user response:

Another solution:

s = "HELLO WORLD"

out = []
for w in map(list, s.split(" ")):
    for i in range(1, len(w), 2):
        w[i], w[i - 1] = w[i - 1], w[i]
    out.append("".join(w))

print(" ".join(out))

Prints:

EHLLO OWLRD
  • Related