How to reverse a string in Python?

In Python, there are several ways to reverse a string. Here are some common methods:

  1. reverse the order
string = "Hello, World!"
reversed_string = string[::-1]
print(reversed_string)
# 输出:!dlroW ,olleH
  1. flipped around
  2. unite
string = "Hello, World!"
reversed_string = ''.join(reversed(string))
print(reversed_string)
# 输出:!dlroW ,olleH
  1. for the purpose of
string = "Hello, World!"
reversed_string = ''
for char in string:
    reversed_string = char + reversed_string
print(reversed_string)
# 输出:!dlroW ,olleH
  1. Using a recursive function:
def reverse(string):
    if len(string) == 0:
        return string
    else:
        return reverse(string[1:]) + string[0]

string = "Hello, World!"
reversed_string = reverse(string)
print(reversed_string)
# 输出:!dlroW ,olleH

These are some common methods, you can choose one based on your preferences and needs.

bannerAds