Python Reverse a String

Document 对象参考手册Python3 Examples

In Python, reversing a string can be achieved in multiple ways. The most common method is using slicing, which is simple and efficient. Below we will show how to use slicing to reverse a string.

Example

def reverse_string(s):
    return s[::-1]

# Example usage
original_string = "Hello, World!"
reversed_string = reverse_string(original_string)
print(reversed_string)

Code explanation:

  • s[::-1]Is the slicing operation in Python, which starts from the end of the string and traverses the entire string with a step of -1, thereby achieving reversal.
  • reverse_stringThe function takes a stringsas a parameter and returns its reversed result.
  • original_stringIs the original string to be reversed.
  • reversed_stringStores the reversed string.
  • print(reversed_string)Outputs the reversed string.

Output:

!dlroW ,olleH

Document 对象参考手册Python3 Examples

Other Extensions