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.
print('CSEstack'[::-1])
Output:
kcatsESC
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]
0
.1
.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])
Output:
ESC
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.
Thanks for this detailed explanation.
You’re welcome, Raman!
Shouldn’t the print statement be like this:
If not enclosed in parentheses, it throws an error.