Python Reverse String

In this article let's try to learn how to reverse a string using a Python program. 

 

write a python program to reverse a string

 

 

There are two ways to reverse a string 

First : Using a python reverse string slice method
Second : Reverse string in python using for loop / reverse string python without slicing

let's try to look into the program and try to solve the string reverse in Python



1) Python reverse string slice method

Ask a user to enter a string using input function and using a string slicing, reverse the given string [::-1] It will reverse a string and print it using a print function.


data = input("Enter a String : ")
info = data[::-1]
print("Reverse of String is ...")
print(info)



OUTPUT:

Enter a String : how are you ?
Reverse of String is ...
? uoy era woh

 

2)  Reverse string in python using for loop

Let's ask a user to enter a string using the input function and use  another variable to store the reverse of a string.  using the following traverse each and every letter of a string and add the letter in front of the reverse string.  once the for loop completes the reverse string will be stored in the second variable

data = input("Enter a String : ")
info = ""
for letter in data:
   info = letter + info

print("Reverse of String is ...")
print(info)


OUTPUT:

Enter a String : are you there ?
Reverse of String is ...
? ereht uoy era




Conclusion : Try the program by yourself by changing the input string.  comment down below if you have any queries



Post a Comment

0 Comments