write a python function to reverse a string
Answers
Answered by
2
Required Answer:-
Question:
- Write a Python function to reverse a string.
Solution:
Here comes the program.
def rev(s):
x=""
for i in range(len(s)-1,-1,-1):
x+=s[i]
return x
s=input("Enter a string: ")
s=rev(s)
print("Reversed string:",s)
Explanation:
Consider a string: Hello
Letter: H e l l o
Index: 0 1 2 3 4
Last index is equal to the length of the string - 1.
So, iterate a loop in the range i = len(s) -1 to 0 and add all the letters in the index and store the result in x variable. Return x.
Using slicing,
def rev(s):
return s[::-1]
s=input("Enter String: ")
s=rev(s)
print("Reversed String:",s)
s[::-1] displays string in reverse order.
See the attachment for output ☑.
Attachments:
Similar questions