Reverse a String in Python 11

Reverse a String in Python CSOTD #11 min read

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

Author

  • Tanmay Sinha

    Founder & CEO of MrProgrammer.in | I help Learning Freaks to Step into the World of Programming and Our Mission is to Provide High Quality and Valuable Content to Our Users! We believe that everyone has the potential to learn to code, and we are committed to making that happen. Our courses are designed to be engaging and interactive, and we offer a variety of learning paths to meet the needs of all learners. We are also committed to providing our learners with the support they need to succeed, and we offer a variety of resources to help learners learn at their own pace. If you are interested in learning to code, we encourage you to check out our courses. We are confident that you will find our content to be high-quality, valuable, and makes sense.

One comment

Leave a Reply