How to Reverse a String in Python

Created
Modified

Using slicing

Slice notation takes the form [start:stop:step].

#!/usr/bin/python3

s = "Hello World"
print(s[::-1])

# syntax
# a[start:stop]  # items start through stop-1
# a[start:]      # items start through the rest of the array
# a[:stop]       # items from the beginning through stop-1
# a[:]           # a copy of the whole array
dlroW olleH

Using reversed Function

The reversed() built-in function returns a reverse iterator. For example,

#!/usr/bin/python3

s = "Hello World"
r = ''.join(reversed(s))
print(r)
dlroW olleH

Using recursion

You can use recursion to reverse a string.

The following example:

#!/usr/bin/python3

def reverse(s):
  if len(s) == 1:
    return s
  
  return s[-1] + reverse(s[:-1])

s = "Hello World"
print(reverse(s))
dlroW olleH

if the string is decent length you'll run into RecursionError.

Python Errors

maximum recursion depth exceeded while calling a Python object:

print(reverse("abcdef"*1000))
RecursionError: maximum recursion depth exceeded while calling a Python object

Related Tags