How do I reverse a string in Python?

To reverse a string in Python, here are the most common and efficient methods:

1. Using Slicing (Most Pythonic)

s = "hello"
reversed_str = s[::-1]  # "olleh"

Explanation:

  • The slice [::-1] reverses the string by stepping backward with a step size of -1.

2. Using reversed() + join()

s = "world"
reversed_str = ''.join(reversed(s))  # "dlrow"

Explanation:

  • reversed(s) returns an iterator over the characters in reverse order.
  • ''.join() combines these characters into a new string.

3. Using a Loop

s = "python"
reversed_str = ""
for char in s:
    reversed_str = char + reversed_str  # Prepends each character
# Result: "nohtyp"

Optimized version (using a list for efficiency):

reversed_str = []
for char in reversed(s):
    reversed_str.append(char)
reversed_str = ''.join(reversed_str)

4. Using a List and reverse()

s = "example"
char_list = list(s)
char_list.reverse()
reversed_str = ''.join(char_list)  # "elpmaxe"

Key Notes

  • Immutability: All methods create a new string (original string remains unchanged).
  • Edge Cases:
  • Empty string: Returns empty.
  • Unicode characters: Handled correctly (e.g., "🚀🌎" → "🌎🚀").
  • Efficiency: Slicing ([::-1]) is fastest and most concise.

Performance Comparison

MethodTime ComplexityUse Case
Slicing ([::-1])O(n)Best for most cases
reversed() + joinO(n)Readable alternative
LoopO(n)Pedagogical/iterative logic
List reverse()O(n)Intermediate list operations

Example with Input/Output

original = "Hello, World!"
reversed_str = original[::-1]
print(reversed_str)  # "!dlroW ,olleH"

When to Use Which?

  • Slicing: Default choice for simplicity and speed.
  • reversed(): Useful in functional programming contexts.
  • Loops: For teaching/learning or custom reversal logic.
  • List reverse(): Rarely needed, but works if already using list operations.

All methods handle standard ASCII and Unicode strings correctly. For advanced scenarios (e.g., grapheme clusters), use libraries like unicodedata.

Leave a Reply

Your email address will not be published. Required fields are marked *