Python function to reverse a string

Document 对象参考手册Python3 Examples

In Python, we can reverse a string in multiple ways. The following is a simple function example that takes a string as input and returns its reversed version.

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:

  1. def reverse_string(s):Defines a function namedreverse_stringthat takes a parameters。
  2. return s[::-1]is the core part of the function.s[::-1]It is a slicing operation in Python, which traverses the entire string from the end with a step of -1, thereby reversing the string.
  3. original_string = "Hello, World!"Defines an original string.
  4. reversed_string = reverse_string(original_string)Callreverse_stringthe function, and store the result inreversed_stringthe variable.
  5. print(reversed_string)Output the reversed string.

Output result:

!dlroW ,olleH

Document 对象参考手册Python3 Examples

Other extensions