Program 13: Reverse a String - 1000+ Python Programs


String Reversal in Python

What is Reversing a String?

    Reversing a string means reversing the order of characters in a given string.

    For example, if we reverse the string "Hello", we get "olleH"


Pseudo Logic

    To reverse a string in Python, follow these steps to build your logic:

    1. Create a method named reverse_string(input_string) that takes in a input_string argument.
    2. Initialize an empty String variable say reversed_string.

    3. Iterate through each character using a for loop of the input string in reverse order.

    4. Now append each character to the reversed_string variable.

    5. Return the reversed_string variable.


Python Reverse String Program

#
# Program 13: String Reversal
# 1000+ Python Programs by Code2care.org
#

def reverse_string(input_string):
    """
    Args:
        input_string (str): The string to be reversed.

    Returns:
        str: The reversed string.
    """
    reversed_string = ''
    # Iterate through each character of the input string in reverse order
    for i in range(len(input_string) - 1, -1, -1):
        # Append each character to the reversed_string variable
        reversed_string += input_string[i]
    # Return the reversed string
    return reversed_string

# Let's try a few examples
print(reverse_string("John"))
print(reverse_string("Stephen"))
print(reverse_string("Andrew"))
print(reverse_string("Harry"))
Output:

nhoJ
nehpetS
werdnA
yrraH


String Reversal using Python Built-in Method

The built-in reversed() function that can be used to reverse a String.

input_str = "Voldomort"
reversed_str = ''.join(reversed(input_str))
print(reversed_str)
Output:

tromodloV

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap