Reverse a string without using reversed() or [::-1]? Reverse a string without using reversed() or [::-1]? python python

Reverse a string without using reversed() or [::-1]?


You can also do it with recursion:

def reverse(text):    if len(text) <= 1:        return text    return reverse(text[1:]) + text[0]

And a simple example for the string hello:

   reverse(hello) = reverse(ello) + h           # The recursive step = reverse(llo) + e + h = reverse(lo) + l + e + h = reverse(o) + l + l + e + h  # Base case = o + l + l + e + h = olleh


Just another option:

from collections import dequedef reverse(iterable):    d = deque()    d.extendleft(iterable)    return ''.join(d)


Use reversed range:

def reverse(strs):    for i in xrange(len(strs)-1, -1, -1):        yield strs[i]...         >>> ''.join(reverse('hello'))'olleh'

xrange or range with -1 step would return items in reversed order, so we need to iterate from len(string)-1 to -1(exclusive) and fetch items from the string one by one.

>>> list(xrange(len(strs) -1, -1 , -1))[4, 3, 2, 1, 0]  #iterate over these indexes and fetch the items from the string

One-liner:

def reverse(strs):    return ''.join([strs[i] for i in xrange(len(strs)-1, -1, -1)])... >>> reverse('hello')'olleh'