In the previous article, we were required to validate if the reversed string or string elements were the same as the one in original ordering. Hence, we saw two ways in which it could be done…in this article we will explore a bit more of the same concept of how to reverse a string in python.
We are supposed to write a program that takes a string from the user and prints the reversed string. For example, if the user gives the program the input “CodeKyro” the program should return the output: “oryKedoC”, if the input provided is “abbac”, the output is “cabba”. However, on the input of a single character it would return the same single character i.e, an input of “a” would result in output “a”.
Implementation to reverse a string in Python
We can use a looping structure to iterate though the string characters and then print them in reverse order. Strings in Python are immutable, so to reverse the string elements we create a new string and then pass it for output.
s=input("Enter a String:") rev=" " for i in s: rev=i+rev print(rev)
Output: Enter a String:abcd dcba
The loop iterates through the character and adds them one by one to the end of the new string. Alternatively, we can use the slice expression to obtain the same end result with shorter and optimized code.
s=input("Enter a String: ") print(s[:: -1])
Output: Enter a String: DADA ADAD
Due to the expression it begins the slice in reverse form the end, uses the step -1 traverses to the beginning of the string and prints the result. In the next article we will discuss how to convert Decimal to Binary in Python.