×

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

Difference Between Python and Scala

What is Python? Python is a high-level general-purpose interpreted programing language. It is used for multi general-purpose work such as language construct as well as its object-oriented approach aims to help...

4 minutes read.

Dictionary to JSON Python

In python JSON (JavascriptObject Notation). In the programming language, the text file is made using the script file.We can use many built-in packages which arenamedJSON.Before using the packages, we have...

3 minutes read.

Python Permutations and Combinations

In mathematics, we all studied what is meant by permutations and combinations. “Permutations” define the way of arranging the elements in sequential order. “Combinations” mean the way of selecting the...

7 minutes read.

Tensorflow Angular in Python

TensorFlow is an open-source, Python-compatible toolkit for numerical computation that accelerates and simplifies the creation of neural networks and machine learning algorithms. They make the interesting notion that models can be...

6 minutes read.

Google Chrome API in Python

Python: 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 faster way....

3 minutes read.

Python RegEx

Python RegEx (python regular expressions) is a concept of writing and finding expressions in a pool of characters easily. A Regular expression (RegEx) is a set of characters that defines search...

10 minutes read.

Python Redis Example

Introduction: Redis, representing Distant Word reference Server, is a kind of key-esteem NoSQL server. Redis is intended to help circle capacity for determination, holding information after power is stopped, and stores information...

5 minutes read.

Python Program to Print all the Prime Number in an Interval

Python Program to Print all the Prime Number in an Interval What is Prime numbers? A prime number is referred to those numbers that can be divisible by them only. In simple words,...

4 minutes read.

Python BytesIO

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Python hasattr() function

Python hasattr() function The hasattr() function in Python returns a Boolean value ‘True’ if the given object has the specified attribute, else it returns False. Syntax hasattr(object, name) Parameter object: it is a required parameter which represents an object. attribute:...

1 minute read.

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.

Python List count() method

Python List count() method The list.count() method returns the number of times x appears in the list. Syntax list.count(x) Parameter x: This parameter represents the value to search for and can contain any iterable (list, set, tuple, etc.) Return This method returns the...

1 minute read.

Method Overloading in Python

Overloading is a capability of a method and operator to behave differently according to the nature of parameters. Overloading is popular because it provides a good number of advantages: Reusability of code.Reduces...

3 minutes read.

Length of Tuple in Python

What is Tuple? Python is a data structure in a python programming language; it is the collection of the objects in a sequence. The tuples are immutable; that is, we cannot...

3 minutes read.

Weight Conversion GUI using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

3 minutes read.

Python format() function

Python format() function The format() function in Python formats a specified value into the given format. A ‘TypeErrorexception’ is raised if the method search reaches the object and the format_spec is non-empty, or if either the format_spec or the...

1 minute read.

Python Control Statements

Control statements are under the roof topic of loops and loops in python are defined as iteratively and repeatedly working on source code. Loop control statements are defined as they...

3 minutes read.

Python Program to Check Leap Year

Python Program to Check Leap Year Leap year: We all know that each year has 365 or 366 days. But whenever a year has 366 days, then the year is said...

2 minutes read.

Python List reverse() method

 Python List reverse() method The list.reverse () method in Python reverses the elements of the list in place. Syntax list.reverse() Parameter NA Example 1 # Python program explaining # the list.reverse() method weekList = ['Sun','Thurs','Mon','Fri', 'Tues', 'Wed'] print("Actual week list: ",weekList) #...

1 minute read.

Curdir Python

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...

3 minutes read.