Write a Python function to reverse given string

1. reverse given string using while loop


def string_reverse(str):
 
    rstr = ''
    index = len(str)
    while index > 0:
        rstr += str[ index - 1 ]
        index = index - 1
    return rstr
print("Reverse string:")
print(string_reverse('hello'))

output:-

Reverse string:
olleh
>>> 

2. Python Reverse String using Slicing


def reverse_slicing(s):
    return s[::-1]

input_str = 'hello'

if __name__ == "__main__":
    print('Reverse String using slicing =', reverse_slicing(input_str))
output:-

Reverse String using slicing = olleh
>>> 

3.Reverse String using For Loop


def reverse_for_loop(s):
    s1 = ''
    for c in s:
        s1 = c + s1  # appending chars in reverse order
    return s1

input_str = 'helloworld'

if __name__ == "__main__":
    print('Reverse String using for loop =', reverse_for_loop(input_str))
output:-
Reverse String using for loop = dlrowolleh
>>> 

4. Reverse a String using join() and reversed()


def reverse_join_reversed_iter(s):
    s1 = ''.join(reversed(s))
    return s1
print(reverse_join_reversed_iter("hello"))
output:-
olleh
>>> 
 
 

Post a Comment

If you have any doubts, Please let me know
Thanks!

Previous Post Next Post