How to reverse a string in Python?

There are several ways to reverse a string in Python. Here are three common methods:

  1. Using string slicing:
string = "Hello, World!" reversed_string = string[::-1] print(reversed_string)

Output: !dlroW ,olleH

  1. Using a loop and concatenation:
string = "Hello, World!" reversed_string = "" for char in string: reversed_string = char + reversed_string print(reversed_string)

Output: !dlroW ,olleH

  1. Using the reversed() function:
string = "Hello, World!" reversed_string = ''.join(reversed(string)) print(reversed_string)

Output: !dlroW ,olleH

All three methods produce the same output, reversing the characters in the original string.