There are a lot of ways to reverse a string in python. Here, I shared some simple methods along with program examples for python string reversal.
1. Slicing
This is the easiest method. The program uses a list slicing method to reverse a string.
text = "Hello World"
reverse_string = text[::-1]
print(reverse_string) # dlroW olleH
2. Built-in Reversed Method
We can also use Python’s built-in reversed()
method to convert a string into a reversed object. Finally, iterate the object using the join()
method to get a reversed string.
text = "Hello World"
reverse_string = ''.join(reversed(text))
print(reverse_string) # dlroW olleH
3. Recursive Function
Here we use a simple recursive function to reverse a string. It will be useful if you would like to reverse multiple strings. You can simply call the function to reverse the text.
def string_reversal(text):
if len(text) == 0:
return text
else:
return string_reversal(text[1:]) + text[0]
text = "Hello World"
reverse_string = string_reversal(text)
print(reverse_string) # dlroW olleH
4. Character Looping
This method also uses a function, but it loops the characters of the string to reverse it.
def string_reversal(text):
reversed_text = ""
for char in text:
reversed_text = char + reversed_text
return reversed_text
text = "Hello World"
reverse_string = string_reversal(text)
print(reverse_string) # dlroW olleH
Recommended Method
Among the above four methods, I would suggest the second method as it is more convenient and easier to implement than other methods.