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?
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
~
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With