There is no built in reverse
function for Python\'s str
object. What is the best way of implementing this method?
If supplying a very conci
a=input()
print(a[::-1])
The above code recieves the input from the user and prints an output that is equal to the reverse of the input by adding [::-1].
OUTPUT:
>>> Happy
>>> yppaH
But when it comes to the case of sentences, view the code output below:
>>> Have a happy day
>>> yad yppah a evaH
But if you want only the characters of the string to be reversed and not the sequence of string, try this:
a=input().split() #Splits the input on the basis of space (" ")
for b in a: #declares that var (b) is any value in the list (a)
print(b[::-1], end=" ") #End declares to print the character in its quotes (" ") without a new line.
In the above code in line 2 in I said that ** variable b is any value in the list (a)** I said var a to be a list because when you use split in an input the variable of the input becomes a list. Also remember that split can't be used in the case of int(input())
OUTPUT:
>>> Have a happy day
>>> evaH a yppah yad
If we don't add end(" ") in the above code then it will print like the following:
>>> Have a happy day
>>> evaH
>>> a
>>> yppah
>>> yad
Below is an example to understand end():
CODE:
for i in range(1,6):
print(i) #Without end()
OUTPUT:
>>> 1
>>> 2
>>> 3
>>> 4
>>> 5
Now code with end():
for i in range(1,6):
print(i, end=" || ")
OUTPUT:
>>> 1 || 2 || 3 || 4 || 5 ||