How to reverse a string in Python
In Python, the fastest and easiest way to reverse a string is the extended slice, [::-1]
.
print("hello world"[::-1]) # dlrow olleh
This article will show you a few ways to reverse a string in Python.
[::-1]
reverse order slice. (Good)[::-1]
slice implement as function. (Good)- Reversed and Join (Reverse String and Words) (Ok)
- Python Loop (Educational purposes)
1. Python Slice [::-1]
In Python, we can use [::-1]
to reverse a string, aka extended slice. The below is the slice syntax:
string[start:stop:step]
start
– Start position, default is 0. (include this string)stop
– Stop position. (exclude this string)step
– Slice the element by step, defaults to 1 – takes every element, if step = 2, takes every 2nd element.
Here is a string "abcdefghijk", along with its internal index.
Index 0 and -1
a b c d e f g h i j k
0 1 2 3 4 5 6 7 8 9 10 (index starts at 0)
-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 (reverse index starts at -1)
1.1 The step defaults to 1. This slice [2:5]
gets the char from index 2 to index 5 (exclude this char).
print("abcdefghijk"[2:5]) # c d e
print("abcdefghijk"[2:5:1]) # c d e
"""
a b {c d e f} g h i j k
0 1 {2 3 4 5} 6 7 8 9 10 = index
"""
1.2 This slice [2:]
gets the char from index 2 to the end of the string.
print("abcdefghijk"[2:]) # c d e f g h i j k
"""
a b {c d e f g h i j k}
0 1 {2 3 4 5 6 7 8 9 10} = index
"""
1.3 For this slice [2::2]
, step is 2, it will get the even indexes (every 2nd index), start from index 2 to the end of the index.
print("abcdefghijk"[2::2]) # c e g i k
"""
a b {c} d {e} f {g} h {i} j {k}
0 1 {2} 3 {4} 5 {6} 7 {8} 9 {10} = index
"""
1.4 For this slice [::-1]
or [-1::-1]
, the result is the same, the string will reverse.
print("abcdefghijk"[::-1]) # k j i h g f e d c b a
print("abcdefghijk"[-1::-1]) # k j i h g f e d c b a
"""
[::] = step default is 1.
|--------------------------------------------------->>>
{a} {b} {c} {d} {e} {f} {g} {h} {i} {j} {k}
{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10}
[::-1] = if step is -1, reverse order.
<<<---------------------------------------------------|
{a} {b} {c} {d} {e} {f} {g} {h} {i} {j} {k}
{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10}
"""
step = -1
In Python slice, if the step is -1
, it means reverse order, and the start position defaults to -1
.
1.5 For this slice [:4:-1]
, the string will reverse until index 4 (5th position, exclude this char).
print("abcdefghijk"[:4:-1]) # k j i h g f
"""
[:4:-1]
<<<--------------------------|
a b c d e {f} {g} {h} {i} {j} {k}
0 1 2 3 4 {5} {6} {7} {8} {9} {10} = index
"""
1.6 For this slice [-2:4:-1]
or [-2:-7:-1]
, the result is the same. This slice gets the char in reverse order, start at index -2 or 9 until index -7 or 4 (exclusive).
print("abcdefghijk"[-2:4:-1]) # j i h g f
print("abcdefghijk"[-2:-7:-1]) # j i h g f
print("abcdefghijk"[9:4:-1]) # j i h g f
print("abcdefghijk"[9:-7:-1]) # j i h g f
"""
<<<-----------------------|
a b c d e {f} {g} {h} {i} {j} k
0 1 2 3 4 {5} {6} {7} {8} {9} 10 = index
-11 -10 -9 -8 -7 {-6} {-5} {-4} {-3} {-2} -1 = index (reverse order)
"""
2. [::-1] as function
The same slice [::-1]
, and it implements as a function.
def reversed_string(val, start=None, stop=None):
return val[start:stop:-1]
print(reversed_string("abcdefghijk")) # k j i h g f e d c b a
print(reversed_string("abcdefghijk", -2, 4)) # j i h g f
3. Reversed and Join
3.1 This Python code snippet uses two build-in functions reserved()
and join()
to reverse a string.
string = "abcdefghijk"
print("".join(reversed(string)))
Output
kjihgfedcba
3.2 If we combine the same technique with a split()
, and we can reverse words.
string = "Hello World Python Slice"
print(" ".join(reversed(string.split(" "))))
Output
Slice Python World Hello
4. Python Loop
This Python code is for good educational purposes, it loops element from the last index to the beginning index, and puts it into a list, in the end, join the list and return a string.
def reverse_a_string(string):
a_list = [] # a new list
index = len(string) # total length of a string, last index
while index: # loop from the last index to the beginning index
index -= 1 # index = index - 1 , reverse one by one
a_list.append(string[index]) # append to the list
return "".join(a_list) # join everything.
result = reverse_a_string("abcdefghijk")
print(result) # kjihgfedcba
Output
kjihgfedcba