In this article we will discuss how to access characters in string by index.

Accessing characters by index in string | indexof

In Python indexing of strings starts from 0 till n-1, where n is the size of string. So characters in string of size n, can be accessed from 0 to n-1.

Suppose we have a string i.e.

Let’s access character at 5th index i.e.

We can access and use the character i.e.

Accessing string elements by negative index

We can also access the character in string using negative indexing i.e.

  • string[-1] will return the last character of string
  • string[-2] returns the second last character of string
  • If string size is n then string[-n] will return the first character of string

For Example :

Output:

Modifying characters in string using []

Python strings are immutable, therefore we can not change content of string using [] operator. If we try to modify the string with [] then it will return error i.e.

It will throw error like this,

Accessing Out Of range character in python string

Accessing element in string that is out of its range i.e. greater than its length, will throw IndexError exception. Therefore we should always check the size before accessing element by index i.e.

or we can can catch the exception too i.e.

What we can do by accessing characters from string by index ?

  • We can loop over the string contents in forward and reverse direction
  • We can slice strings to get sub strings.

We will discuss this in next articles.

Complete example is as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.