×

Python String Negative Indexing

This page contains all the information how to use “Negative indexing“ in Python with the help of using slicing.

What is an Index?

An index is a numeric value, which is assigned to individual characters of the iterables. An index is used when the user wants to access individual characters of the iterables. For example, take a string “loyd" containing four characters. Therefore, it contains four indexes that range from zero to three. For any iterable, the numeric values of the indexes range from zero to "n-1”, where n is the number of characters presented in the string.

Usage of Slicing in Python

In order to print the desired part of an iterable, we make use of a quality of python, which is known as “ Slicing “. It selects a start and an end index given by the user and prints the characters of the iterable using the concatenation method.

Syntax of Slicing

inputStr[ start: end ]

1 Example: Indexing by Slicing

# considering a variable and assigning a string to it
inputStr = " Hello "
# printing the letters of the string in reverse order
print(inputStr[ 1:3])

Output

Hel

2 Example: Indexing by Slicing

# considering a variable and assigning a string to it
inputStr = " Hello "
# printing the letters of the string in reverse order
print(inputStr[ 2:0])

Output

leH

3 Example: Indexing by Slicing

# considering a variable and assigning a string to it
inputStr = " Welcome to my world "
# printing the letters of the string in reverse order
print(inputStr[ 1: 20])

Output

Welcome to my world

What is Negative Indexing

Python has an in-built feature called “negative indexing “, which is used to select and print the desired part of an iterable in reverse order. Hence, negative indexing is also called " reverse indexing”. The numerical values for negative indexing do not start with zero, and they start with " -1 ".

In a string, the last character of the string is assigned with the value " -1 ". The numerical values for negative indexing range from “ -1” to “-n ”, where n is the number of characters that are present in the string. Let us consider an example of negative indexing by using the string mentioned above, " loyd ". In zero-based indexing, the first character in the string “l” is given the index “0 ", but, in negative-based indexing, the first character " l” is Assigned with the index “ -4”. Similarly, the last character “d” is given the index “ -1” in negative indexing.

Implementation of Negative Indexing

To implement negative indexing or reverse indexing in python, we make use of the “extended slicing “concept. In the extended slicing concept, the syntax of slicing is modified and added with a negative step size. This makes the slicing in reverse order (i.e., backwards). This is done with the help of step " -1”.

Syntax of Extended Slicing

inputStr[ start: end : step ]

Program 1: By using Extended Slicing

# considering a variable and assigning a string to it
inputStr = " Hello "
# printing the letters of the string in reverse order
print(inputStr[ -1: :-1])

Output

olleH

Program 2:  By using Extended Slicing

# considering a variable and assigning a string to it
inputStr = " Welcome to my world "
# printing the letters of the string in reverse order
print(inputStr[ -1: :-1])

Output 2

dlrow ym ot emocleW

Program 3: By using Extended Slicing

# considering a variable and assigning a string to it
inputStr = " Congratulations !! You have learnt Negative Indexing in Python."
# printing the letters of the string in reverse order
print(inputStr[ 1::100])

Output

nohtyP ni gnixednI evitageN tnrael evah uoY !!snoitalutargnoC

Pros of Extended Slicing in Python

  1. The usage of reverse indexing is done faster by using extended slicing.
  2. The in-built method is more convenient and easier to use.
  3. Takes fewer lines of code, which decreases the margin of error.

Conclusion

This feature of python makes the process easier using reverse indexing while we use the for loop to print character backwards,


Related Topics

Python List sort() method

The list.sort () method in Python sorts the items of the list in place. Syntax list.sort(key=None, reverse=False) Parameter reverse: If a Boolean value ‘True’ is passed, the  sorting will be done in the descending order else for ‘False’...

2 minutes read.

First Unique Character in a String Python

This article aims to introduce you to strings and how to create a string in Python, and then we will solve a simple yet exciting DSA (Data Structures and Algorithms)...

3 minutes read.

Python String Variable

Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

4 minutes read.

Artificial intelligence mini projects ideas in python

Artificial intelligence "The human race started from the invention of the wheel", and today we are about to advance to the Industrial level 4.0, where machines can work, talk, think and...

6 minutes read.

Python SymPy

A Python package for symbolic mathematics is called SymPy. Its goal is to develop into a fully-fledged computer algebra system (CAS) while maintaining the code as straightforward as possible to...

3 minutes read.

Python Modulo

For basic calculations, Python provides operators. Python supports a broad range of Arithmetic Operators to do arithmetic, as given below: +Addition*Multiplication-Subtraction/Division//Floor division**Exponentiation%Remainder/Modulus As you can see, one of these basic arithmetic operators...

8 minutes read.

Defaultdict in Python

In this tutorial, we will study What is defaultdict in Python We will understand it with the aid of certain examples. Before this, we will have a look at dictionaries...

3 minutes read.

How to handle exceptions in python

Prerequisite: Exceptions and errors in Python What are Exceptions? Exceptions are run-time errors that unexpectedly occur and crash a program. When occurred, it alters the flow of the program. These errors are...

9 minutes read.

Data Drop in Python

Introduction You'll understand how to delete a group of rows from a Pandas dataframe in this article.You can read this article on How to Drop Columns in Pandas to find out...

6 minutes read.

How to declare array in python

How to declare array in python? Arrays are a great way of storing our numeric values into a variable in continuous locations. For declaring an array in C language, we used...

4 minutes read.

Return Statement In Python

Python Return Statement The return statement is generally used for the execution ending and returns the value back to the caller. The return statement can return all types of values and...

2 minutes read.

Python Dictionary Methods

Python Dictionary Methods Python has a set of built-in methods that dictionary objects can call. All the python dictionary methods are as follow: Methods Description clear() The dictionary.clear() method removes all the elements...

3 minutes read.

Abstraction in Python

What is meant by abstraction generally? A very general notion of a thing or work is known as abstract. To be more precise, the process of having a brief idea but...

4 minutes read.

How to get Time in seconds in Python

Python's time module source shows that are based on time. The time() method is used by developers and returns the current time as a UNIX timestamp. A UNIX timestamp is...

4 minutes read.

Python Logical Operators

In python, there are many operators which we use in our program. Operators are used in manipulating a particular value or operand. Logical operators are used mainly to evaluate an...

7 minutes read.

Crash Course on Python by Google

There is a new, free Python programming course offered by Google on Coursera. No programming experience is necessary. There are numerous Python courses available, but when you learn that Google is...

5 minutes read.

Subprocess in Python

In this tutorial, we will understand what is a subprocess in python and will understand how to use it. Subprocess A subprocess is a very prevailing portion of the python library. It...

3 minutes read.

Merge Sort using Python

Merge Sort is a technique that is used for sorting elements in an array using a special method known as divide and conquer. It is the best example of the...

5 minutes read.

What is Python 2

Python is a widely used high-level language. The initial work on developing python was begun in the late 1980s. In 1989, Guido Van Rossum started to work on it. Initially,...

3 minutes read.

Python Network Programming

In network programming, python plays a very important role. Python provides full support for encoding and decoding data and network protocol in its standard library. Writing a network program in...

3 minutes read.