The string is nothing but a set of characters. The typical way of reverse the string is to swapping the character positions.
There is a major disadvantage to it. You have to loop over all the characters of the string. Not much convenient.
There is another way of reversing the string in Python.
Simple one-liner solution.
Reverse string in Python is very much simple. Simple code as ‘CSEStack'[::-1] reverse the string.
Though it is a simple Python code, it is important to understand how does the string gets reversed.
This syntax of string manipulation is called as Extended Slice Syntax. It is defined as
[begin: end: step]
This feature was added in all the versions after Python 2.3. This is also supported on Python 3.
This is one of the simple Python tricks for competitive coding.
strName = 'CSE' print(strName[::-1])
Extended slice syntax also works for the List in Python.
You can use this technique to identify if the given string is palindrome or not.
There are many different ways of reversing a string in Python. This is the simplest one to reverse string in Python without using function.
You can try these program related to the reversing string.