What is a Negative Indexing in Python?


Negative Indexing is used to in Python to begin slicing from the end of the string i.e. the last. Slicing in Python gets a sub-string from a string. The slicing range is set as parameters i.e. start, stop, and step.

Syntax

Let us see the syntax −

#slicing from index start to index stop-1
arr[start:stop]

# slicing from index start to the end
arr[start:]

# slicing from the beginning to index stop - 1
arr[:stop]

# slicing from the index start to index stop, by skipping step
arr[start:stop:step]

If the values above are in negative, that would mean negative indexing i.e. slicing from the end of the string.

Slice a String with Negative Indexing

Example

# Create a String myStr = 'Thisisit!' # Display the String print("String = ", myStr) # Slice the string # Negative Indexing print("String after slicing (negative indexing) = ", myStr[-4:-1])

Output

String =  Thisisit!
String after slicing (negative indexing) =  sit

Slice a String with Negative Indexing and set a step

The slicing range is set as parameters i.e. start, stop, and step. For negative indexing, set the start and stop as negative values i.e., slice from the end −

Example

# Create a String myStr = 'Thisisit. We did it!' # Display the String print("String = ", myStr) #Slice the string # Negative Indexing with step print("String after slicing (negative indexing) = ", myStr[-9:-3:2])

Output

String =  Thisisit. We did it!
String after slicing (negative indexing) =  edd

Reverse the order of a string with Negative Indexing

To display the 1st element to last element in steps of 1 in reverse order, we use the [::-1]. The [::-1] reverses the order.

Example

Let’s see the example

myStr = 'Hello! How are you?' print("String = ", myStr) # Slice print("Reverse order of the String = ", myStr[::-1])

Output

String =  Hello! How are you?
Reverse order of the String =  ?uoy era woH !olleH

Updated on: 25-Aug-2023

36K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements