How to reverse a String in Python
Learn how to reverse Strings in Python using slicing.
This article explains how to reverse a String in Python using slicing.
There is no built-in
string.reverse() function. However, there is another easy solution.
Use Slicing to reverse a String¶
The recommended way is to use slicing.
my_string = "Python" reversed_string = my_string[::-1] print(reversed_string) # nohtyP
Slicing syntax is
[start:stop:step]. In this case, both start and stop are omitted, i.e., we go from start all the way to the end, with a step size of -1. As a result, the new string gets reversed.
This is not an in-place modification, so the original String gets not changed.
Another option (but slower) is to combine
my_string = "Python" reversed_string = ''.join(reversed(my_string)) print(reversed_string) # nohtyP print(reversed(my_string)) # <reversed object at 0x1048b8d00>
reversed() returns an object of type
reversed, which is an iterable that needs to be combined back into a String.
More String Methods¶
You can learn more about Strings in these articles
FREE VS Code / PyCharm Extensions I Use
✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link** This is an affiliate link. By clicking on it you will not have any additional costs. Instead, you will support my project. Thank you! 🙏