Python Reverse a String
In Python, a string can be reversed in several ways. The most common is a slice operation, which is simple and efficient. Below we 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
)
(
reversed_string
)
Code analysis:
s[::-1]is a Python slice operation that means traversing the whole string from the end with a step of -1, thereby reversing it.reverse_stringThe function takes a stringsas a parameter and returns its reversed result.original_stringis the original string we want to reverse.reversed_stringstores the reversed string.print(reversed_string)Print the reversed string.
Output result:
!dlroW ,olleH
Python3 Examples