Python function to reverse a string
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)
return s[::-1]
# Example usage
original_string = "Hello, World!"
reversed_string = reverse_string(original_string)
print(reversed_string)
Code explanation:
def reverse_string(s):Defines a function namedreverse_stringthat takes a parameters。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.original_string = "Hello, World!"Defines an original string.reversed_string = reverse_string(original_string)Callreverse_stringthe function, and store the result inreversed_stringthe variable.print(reversed_string)Output the reversed string.
Output result:
!dlroW ,olleHOther extensions
Python3 Examples