How to Reverse String in Python without using Function?

How to Reverse String in Python without using Function?

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.

Python interview questions and answers

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.

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]
  • begin: Begin defines the starting index of string to clip. If you don’t mention the “begin” index value, it takes default as the index 0.
  • end: End defines the last index of string to be sliced. If you don’t mention the “end” index, it takes default 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.

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.

Code to Reverse String in Python without Using Function

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.

3 Comments

  1. Shouldn’t the print statement be like this:

    print(str[::-1])

    If not enclosed in parentheses, it throws an error.

Leave a Reply

Your email address will not be published. Required fields are marked *