Reversing stringsΒΆ

The easiest way to reverse a string is using slicing notation.

In [1]:
def reverse_str(s):
    return s[::-1]
In [2]:
s = "praxis"

Let's now write something that doesn't use slicing. Instead, let's do the following: start with an empty string res. Then add s[len(s)-1] to it. Then add s[len(s)-2] to it, and so on, down to s[0].

In [3]:
def reverse_str2(s):
    res = ""
    for i in range(len(s)-1, -1, -1):
        res = res + s[i] #res += s[i] is more concise
    return res

Finally, let's reverse a string by going through its characters from the left to right. Here is the idea:

    res = ""
    res = "p" + res #"p"
    res = "r" + res #"rp"
    res = "a" + res #"arp"
    res = "s" + res #"sixarp"

We need to change the function above just a little bit to accomplish this:

In [4]:
def reverse_str3(s):
    res = ""
    for i in range(len(s)):
        res = s[i] + res

The more usual way to write this function is

In [5]:
def reverse_str4(s):
    res = ""
    for ch in s:
        res = ch + res
    return res