How to Reverse String in Python using Extended Slice Syntax?
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 of 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.
Reversing Python string using Extended Slice Syntax
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.
- begin: Begin defines the starting index of string to clip. If you don’t mention begin index value, it takes default as index 0.
- end: End defines the last index of string to be sliced. If you don’t mention the end index, it takes defaults as the last index of string
- step: It defines steps to be jumped from one char to next char. The default step value is 1.
Code to Reverse String in Python
strName= 'CSE' print strName[::-1]
Extended slice syntax also works for the List in python.
What are the other ways of reversing the string in Python? Write in the comment.