Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Implement a Function to Reverse a String

Python Implement a Function to Reverse a String

Document Object Reference Manual Python3 Examples

In Python, there are several ways to reverse a string. Here 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 analysis:

  1. def reverse_string(s): defines a class named reverse_string function, which takes a parameter s。
  2. return s[::-1] is the core part of the function.s[::-1] is a Python slice operation that traverses the whole string from the end with a step of -1, thereby reversing the string.
  3. original_string = "Hello, World!" Define an original string.
  4. reversed_string = reverse_string(original_string) called reverse_string function and store the result in reversed_string variable.
  5. print(reversed_string) Print the reversed string.

Output result:

!dlroW ,olleH

Document Object Reference Manual Python3 Examples