Landon G
Landon G

Reputation: 839

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?

Upvotes: 6

Views: 2318

Answers (5)

Varun Chandran
Varun Chandran

Reputation: 671

Using Kotlin,

fun reverseWords(str: String) =str.split(" ").joinToString(" ") { it.reversed() }

Upvotes: 0

Paul M.
Paul M.

Reputation: 10809

Nothing too different from what's been posted so far:

string = "This is the string"
string_reversed = " ".join(["".join(reversed(word)) for word in string.split()])
print(string_reversed)

edit Just read the original post again, sorry.

Upvotes: 0

Chiheb Nexus
Chiheb Nexus

Reputation: 9267

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.

Upvotes: 1

ealeon
ealeon

Reputation: 12460

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

Upvotes: 2

hootnot
hootnot

Reputation: 1014

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

~

Upvotes: 6

Related Questions