Python string index
Indexing in python
What is an index?
The index refers to a position within an ordered list. Python string is a group of characters, each character is given an index.
Index always starts from Zero indexes.
For Example:- For Python String s=”tech”
String breaks in character and each character are given an index as shown below
We can access a character in a string by its index as
Index number indicates the value contained at an Index position.
- In python, there is positive and negative index.
Python arrays & list items can be accessed with positive or negative numbers (also known as index
- Python Positive index
What is a positive index in python?
A value starting from 0 (contains positive numbers) is a positive index.
We can access a positive index from left to right.
- Python negative index
This is also known as reverse indexing python
What is a negative index in python?
A negative index is used in python to index starting from the last element.
Python will traverse the list from right to left for the negative index
A value starting from -1(contains an only negative number) is negative index.
We access negative index from right to left.
- The specialty of python is having a positive index and negative index.
- Example: – consider above image our string is A = “technical”
- You can access the value stored at index either by positive index or by negative index. Using positive index access string characters
A => t
A => e
Using negative index access string characters
A[-1] => l
A[-2] => a
- And if you are accessing index which is not available (our of index value) then you will get an index error.
- Example: –
A => Error
Why python provided negative index?
To provide flexibility to programmer python has a negative index. So that programmer can use from start or from an end. Programmers are flexible to work on Strings and list.