pythonstring

Reversing string characters while keeping them in the same position


I'm looking to reverse a set of strings while keeping them in the same positions and also trying not to use slicing or reverse(). So if I had:

string = 'This is the string'

Using the reverse function, it would return:

'sihT si eht gnirts'

I made a function that does everything correct except for positioning:

def Reverse(string):
   length = len(string)
   emp = ""
   for i in range(length-1,-1,-1):
       emp += length[i]
   return emp

which returns;

gnirts a si sihT      # correct reverse, wrong positions

How can I get this reversed string back into the correct positions?


Solution

  • def Reverse(string):
        length = len(string)
        emp = ""
        for i in range(length-1,-1,-1):
            emp += string[i]
        return emp
    
     myString = 'This is the string'
     print ' '.join([Reverse(word) for word in myString.split(' ')])
    

    OUTPUT

    sihT si eht gnirts