How to reverse a string in Python?

Published on Aug. 22, 2023, 12:17 p.m.

There are several ways to reverse a string in Python:

  1. Using slicing - this is the simplest and most efficient way to reverse a string in Python:
my_string = "hello, world!"
reversed_string = my_string[::-1]
print(reversed_string)

Output:

"!dlrow ,olleh"
  1. Using a loop - another way to reverse a string is to iterate over each character in the string and build a new string in reverse order:
my_string = "hello, world!"
reversed_string = ""
for char in my_string:
    reversed_string = char + reversed_string
print(reversed_string)

Output:

"!dlrow ,olleh"
  1. Using the join() method and a reversed iterator - this method involves converting the string to a list of characters, reversing the list using a reversed iterator, and then joining the characters back together:
my_string = "hello, world!"
reversed_list = reversed(list(my_string))
reversed_string = "".join(reversed_list)
print(reversed_string)

Output:

"!dlrow ,olleh"

All of these methods will reverse a string in Python. The first method using slicing is the most efficient in terms of code length and execution time.

Tags: