How to Reverse a String in Python: 3 Easy Methods with Code
This Snippet is coded by a user inOnline python Compiler. You can see and run this code too.
زبان: python
Reversing a string in Python means producing a new string with the characters in the opposite order. Python strings are immutable, so each method returns a new string rather than modifying the original. The fastest and most Pythonic approach is slicing with s[::-1]: the slice starts at the end, stops at the beginning, and steps backward by one. Another readable option is ''.join(reversed(s)), which creates a reverse iterator and joins its characters. A manual loop can also build the result by prepending each character, though it is less efficient for large inputs.
The code above demonstrates all three methods with a sample input. For example, passing 'Hello, World!' to any reversal function returns '!dlroW ,olleH'. Empty strings and single-character strings work correctly and return unchanged results, while Unicode text is reversed at the code-point level.
Time complexity is O(n) for every method because each character must be visited once. Space complexity is O(n) because the reversed string requires new memory. Slicing is usually the best choice for readability and performance; reversed() is useful when working with iterators; manual concatenation should be avoided in tight loops because repeated string creation can add overhead. Use the slicing method in most production code.