Python program to reverse a string:
There are three ways to reverse a string in Python:
1st way: Using Slice Operator:
(To learn about slice operator click here)
1
2
3
4 | string_data=input("Enter data you want to reverse") result=string_data[::-1] print("The string data you entered is :", string_data) print("The reversed string is:", result)
|
2nd way: Using reversed() function:
Python provides inbuilt function reversed()
It returns reversed object and you can use join() method of strings to get your required output form reversed object.
1
2
3
4
5
6
7 | string_data=input("Enter data you want to reverse") reversed_object=reversed(string_data) print("The string data you entered is :", string_data) for character in reversed_object: print(character,end='') print() print(type(reversed_object)) |
3rd way : Using While loop:
1
2
3
4
5
6
7
8 | string_data=input("Enter data you want to reverse: ") result="" i=len(string_data)-1 while i>=0: result=result+string_data[i] i=i-1 print("The string data you entered is :", string_data) print("String data after reversal: ", result) |
No comments:
Post a Comment