Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing string characters while keeping them in the same position

Tags:

python

string

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?

like image 292
Landon G Avatar asked Feb 07 '19 00:02

Landon G


Video Answer


3 Answers

Guess you want:

string = 'This is the string'

def Reverse(string):
    return ' '.join([s[::-1] for s in string.split(' ')])

print(Reverse(string))

Gives:

sihT si eht gnirts

~

like image 142
hootnot Avatar answered Oct 18 '22 17:10

hootnot


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
like image 38
ealeon Avatar answered Oct 18 '22 18:10

ealeon


Here is another way using two for loops and str.split():

def reverse_pos(string):
    a = ''
    splitted = string.split()
    length = len(splitted)
    for i, elm in enumerate(splitted):
        k = ''  # temporar string that holds the reversed strings
        for j in elm:
            k = j + k
        a += k
        # Check to add a space to the reversed string or not
        if i < length - 1:
            a += ' '
    return a


string = 'This is the string'
print(reverse_pos(string))

Or better:

def reverse_pos(string):
    for elm in string.split():
        k = ''  # temporar string that holds the reversed strings
        for j in elm:
            k = j + k
        yield k


string = 'This is the string'
print(' '.join(reverse_pos(string)))

Output:

sihT si eht gnirts

NB: The main idea here is split by spaces and reverse each elmement. This will reverse and keep the words in their position in the primary string.

like image 1
Chiheb Nexus Avatar answered Oct 18 '22 19:10

Chiheb Nexus