Monday, August 5, 2024

Nitheen Kumar

Write a function to reverse a string in Python

Certainly! You can reverse a string in Python using several approaches. Here are a few methods to achieve this:

  1. Using slicing: Python strings support slicing, and you can reverse a string s using the slicing technique s[::-1].
def reverse_string(s):
return s[::-1]
  1. Using a loop: Iterate over the string in reverse order and build the reversed string character by character.
def reverse_string(s):
reversed_str = '' for char in s: reversed_str = char + reversed_str return reversed_str
  1. Using join and reversed: Convert the string into a list of characters, reverse the list, and join it back into a string.
def reverse_string(s):
return ''.join(reversed(s))

Write a function to reverse a string in Python

All of these functions will reverse a given string s. Here's how you can use them:

# Example usage:
input_str = "Hello, World!" print(reverse_string(input_str)) # Output: "!dlroW ,olleH"

Choose the method that suits your preference or fits best with the rest of your code!

Subscribe to get more Posts :