In this article, we will discuss reversing a string in Python. We will look into different approaches.
1. Naive method
In this naive approach, we will loop through each letter in the string and joins them to form a reverse string as shown below.
def reverse_string(txt):
rev_text = ""
for letter in txt:
rev_text = letter + rev_text
return rev_text
rev_str = reverse_string("hello")
print(f"Reversed string : {rev_str}")
Output
Reversed string : olleh
2. Reverse using list.reverse()
In this approach, we will convert a string to a list, then reverse it using the list.reverse() method. Again the list is converted back into a string.
def reverse_string(txt):
lst_txt = list(txt)
lst_txt.reverse()
rev_text = "".join(lst_txt)
return rev_text
rev_str = reverse_string("apple")
print(f"Reversed string : {rev_str}")
Output
Reversed string : elppa
3 . Reverse using the reversed method
The string is revered using the inbuilt Python method reversed, it will return a reverse iterator. It is converted back to a string.
def reverse_string(txt):
rev_iter = reversed(txt)
rev_text = "".join(rev_iter)
return rev_text
rev_str = reverse_string("cloud")
print(f"Reversed string : {rev_str}")
Output
Reversed string : duolc
4. Reverse using the string slicing
This is the simplest method to reverse a string in Python. A string slice has the following format
string[start:stop:step]
- start: start position of the character
- end : End position of the character
- step: Number of characters to jump after an iteration
To reverse a string we can simply use string[ : :-1], which will process the string in the reverse order (because step is -1) and returns the reversed string.
>>> txt = "hello"
>>> txt[::-1]
'olleh'
5. Reverse a string using list comprehension
In this method, we will use list comprehension to reverse the string in Python. The range function is used to generate an index of the character. We will use the reversed index from range(len(txt)-1, -1 , -1) function.
def reverse_string(txt):
rev_iter = [ txt[i] for i in range(len(txt)-1,-1,-1)]
rev_text = "".join(rev_iter)
return rev_text
rev_str = reverse_string("happy")
print(f"Reversed string : {rev_str}")
Output
Reversed string : yppah
One-liners to reverse a string in Python
We can use the following one-liners to reverse a string.
>>> txt = "hello world"
>>> txt[::-1]
dlrow olleh
>>> "".join(reversed(txt))
dlrow olleh
Conclusion
There you have it, different methods to reverse a string in Python.