string indexing in python example

String indexing in Python with Examples

String indexing in Python allows you to access each characters in string individually through indexes. Strings in Python are ordered sequence of characters. In this tutorial you will learn string indexing syntax with examples.

String indexing in Python

String indexing in Python is zero-based i.e., first character in the string has index value “0” and the next character in the string has value “1” and so on.

There are two types of sting indexing: positive string indexing and negative string indexing. Let’s understand those with following examples.

string indexing in python example

Positive string indexing – Python example

Positive string indexing is nothing but using positive number when you write string index to retrieve a character from a string.

For example, to write a string index to return letter “e” from the string “Hello World”, you need to write the following code.

>>> mystring = "Hello World"

>>> mystring
'Hello World'

>>> mystring[1]
'e'

Similarly, to return letter “H” from the above string you need to write the following code. Because, the first character ‘H’ in the string has index value zero.

>>> mystring[0]
'H'

To fetch the last character from string, you can either use index or the formula as shown below.

>>> mystring[10]
'd'

>>> mystring[len(mystring) - 1]
'd'

Note, the last character’s index value is “10”. And if you try to use index value beyond the range then you will get the following error.

>>> mystring[11]

---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-38-5e4046356d12> in <module>
----> 1 str[11]

IndexError: string index out of range

Negative string indexing – Python example

Below are some examples for negative string indexing. Negative string is nothing but using negative number when you write string index to retrieve a character from a string.

For example, to fetch the last character from the string using negative string indexing.

>>> mystring[-1]
'd'

Note, we have used negative number “-1” .

Similarly, to retrieve the first character using negative string indexing you can do the following.

>>> mystring[-len(str)]
'H'

or

>>> mystring[-11]
'H'

Note, if the string is empty you will get IndexError: string index out of range as the length of the given string is 0.

That’s it. You had learnt what is positive string indexing and negative string indexing with examples in Python programming.

Hope it helped 🙂

You’ll also like:

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments