Python Implement a Function to Reverse a String
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
)
(
reversed_string
)
Code analysis:
def reverse_string(s):defines a class namedreverse_stringfunction, which takes a parameters。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.original_string = "Hello, World!"Define an original string.reversed_string = reverse_string(original_string)calledreverse_stringfunction and store the result inreversed_stringvariable.print(reversed_string)Print the reversed string.
Output result:
!dlroW ,olleH
Python3 Examples