Python Program to Reverse a Given String
This page contains a Python program that reverses a given string. The program uses basic string manipulation techniques to achieve this task.
Program Explanation
The Python program to reverse a string follows these steps:
- Define the main function: Create a function named
reverse_string
that takes a string as input and returns the reversed string. - Input String: Define a string that you want to reverse.
- Reverse the String: Use slicing to reverse the string.
- Print the Result: Output the reversed string to the console.
Python Program Code
# Python program to reverse a given string
def reverse_string(s):
"""
Function to reverse a given string.
:param s: The string to be reversed.
:return: The reversed string.
"""
# Reverse the string using slicing
return s[::-1]
def main():
# Define the string to be reversed
original = "Hello, World!"
# Call the reverse_string function and store the result
reversed_string = reverse_string(original)
# Print the original and reversed strings
print("Original String: ", original)
print("Reversed String: ", reversed_string)
# Entry point of the program
if __name__ == "__main__":
main()
Program Details
The Python program contains the following components:
reverse_string
Function: This function takes a string as input, reverses it using slicing, and returns the reversed string.main
Function: The main function defines the original string, calls thereverse_string
function, and prints both the original and reversed strings.if __name__ == "__main__"
: This construct ensures that themain
function is called only when the script is run directly, not when it is imported as a module.
Running the Program
To run the program:
- Save the code in a file named
reverse_string.py
. - Run the program using the command:
python reverse_string.py
.
Explanation of the Python Program:
- Function Definition:
- The function
reverse_string
takes a strings
as an argument and returns the reversed string using slicing (s[::-1]
).
- The function
- Main Function:
- Initializes a string
original
with the value “Hello, World!”. - Calls the
reverse_string
function and stores the result inreversed_string
. - Prints both the original and reversed strings to the console.
- Initializes a string
- Entry Point:
- The
if __name__ == "__main__"
construct ensures that themain
function is called only when the script is executed directly, not when it is imported as a module.
- The