Python Program to Reverse a Given String

 

 

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:

  1. Define the main function: Create a function named reverse_string that takes a string as input and returns the reversed string.
  2. Input String: Define a string that you want to reverse.
  3. Reverse the String: Use slicing to reverse the string.
  4. 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 the reverse_string function, and prints both the original and reversed strings.
  • if __name__ == "__main__": This construct ensures that the main 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:

  1. Save the code in a file named reverse_string.py.
  2. Run the program using the command: python reverse_string.py.

 

Explanation of the Python Program:

  1. Function Definition:
    • The function reverse_string takes a string s as an argument and returns the reversed string using slicing (s[::-1]).
  2. Main Function:
    • Initializes a string original with the value “Hello, World!”.
    • Calls the reverse_string function and stores the result in reversed_string.
    • Prints both the original and reversed strings to the console.
  3. Entry Point:
    • The if __name__ == "__main__" construct ensures that the main function is called only when the script is executed directly, not when it is imported as a module.

Leave a Reply

Your email address will not be published. Required fields are marked *