Skip to content
Home » Blogs » Reverse a String in Python CSOTD #1

Reverse a String in Python CSOTD #11 min read

Reverse a String in Python 11

Today’s Code Snippet of the Day will reverse a string in Python and show the text (string) in reversed form. Let’s illustrate this with a simple “hello world” program, In the example the text placed inside the string will appear as “!dlrow ,olleH”.

Code:

def reverse_string(string):
  """Reverses a string.

  Args:
    string: A string.

  Returns:
    A string with the characters in reverse order.
  """

  reversed_string = ""
  for i in range(len(string) - 1, -1, -1):
    reversed_string += string[i]
  return reversed_string


# Example usage:

string = "Hello, world!"
reversed_string = reverse_string(string)

print(reversed_string)

Output:

!dlrow ,olleH

We can use the reverse string feature in a variety of tasks such as text processing, data analysis, and cryptography. It is also a good example of a simple but useful function that can be written in Python.

Tanmay Sinha

1 thought on “Reverse a String in Python CSOTD #11 min read

  1. Pingback: Find the Largest Number in an Array | CSOTD #2 - Mr Programmer

Leave a Reply