Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Functions

Function to reverse a string - Python Program

Example 1 :

def reverse_string(s): """Return reversed string.""" return s[::-1] print(reverse_string("Python"))

Output

 
OUTPUT  :
nohtyP

Example 2 : Advanced Program

def reverse_string(s): """ Reverses a given string. Args: s: The input string to be reversed. Returns: The reversed string. """ return s[::-1] # Example Usage and Output: input_string_1 = input("Enter A String : ") reversed_string_1 = reverse_string(input_string_1) print(f"Original string: '{input_string_1}'") print(f"Reversed string: '{reversed_string_1}'") input_string_2 = "Python is fun" reversed_string_2 = reverse_string(input_string_2) print(f"Original string: '{input_string_2}'") print(f"Reversed string: '{reversed_string_2}'") input_string_3 = "" reversed_string_3 = reverse_string(input_string_3) print(f"Original string: '{input_string_3}'") print(f"Reversed string: '{reversed_string_3}'")

Output

 
OUTPUT  :
Enter A String  : Hello
Original string: 'Hello'
Reversed string: 'olleH'
Original string: 'Python is fun'
Reversed string: 'nuf si nohtyP'
Original string: ''
Reversed string: ''

Explanation:

Function Definition:

The code defines a function named reverse_string that takes one argument, s, which represents the string to be reversed.

String Slicing:

The core of the reversal is s[::-1]. This is a Python string slicing technique:

  • The first colon indicates the start of the slice (defaulting to the beginning of the string).
  • The second colon indicates the end of the slice (defaulting to the end of the string).
  • The -1after the second colon specifies a step of -1, which means the slice iterates through the string in reverse order, character by character.