Python : How to access characters in string by index ?

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.

sampleStr = "Hello, this is a sample string"

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

sampleStr[5]

We can access and use the character i.e.

# Access character at index 5
print( "Character at index 5 is : " , sampleStr[5] )

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 :

sampleStr = "Hello, this is a sample string"

print( "Last character in string : " , sampleStr[-1] )
print( "Second Last character in string : " , sampleStr[-2] )
print( "First character in string : " , sampleStr[ -len(sampleStr) ] )

Output:

Last character in string :  g
Second Last character in string :  n
First character in string :  H

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.

sampleStr = "Hello, this is a sample string"

'''
Modifying character in string by Index
As strings are immutable so we can modify the contents of string in python
'''
sampleStr[5] = 's'

It will throw error like this,

TypeError: 'str' object does not support item assignment

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.

sampleStr = "Hello"

#Handle Out Of Range Error by try / except
try :
    print( sampleStr[50] )
except IndexError:
    print ("Index : Out of range")    

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

sampleStr = "Hello"

# Check the size of string before accessing character by index
n = 50    
if n < len(sampleStr) :
    print( sampleStr[50] )
else :         
    print ("Index : Out of range")

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,

def main():
    
    sampleStr = "Hello, this is a sample string"
    
    '''
    Accessing character in string by Index
    '''
    # Access character at index 5
    print( "Character at index 5 is : " , sampleStr[5] )

    '''
    Accessing character in string by Negative Index
    '''
    
    print( "Last character in string : " , sampleStr[-1] )
    
    print( "Second Last character in string : " , sampleStr[-2] )
    
    print( "First character in string : " , sampleStr[ -len(sampleStr) ] )
        
    '''
    Modifying character in string by Index
    As strings are immutable so we can modify the contents of string in python
    '''
    #sampleStr[5] = 's'

    '''
    Accessing Out of range elements in string will cause IndexError
    '''    
    
    #Handle Out Of Range Error by try / except
    try :
        print( sampleStr[50] )
    except IndexError:
        print ("Index : Out of range")    
    
    # Check the size of string before accessing character by index
    n = 50    
    if n < len(sampleStr) :
        print( sampleStr[50] )
    else :         
        print ("Index : Out of range")
           
if __name__ == '__main__':
    main()

Output:

Character at index 5 is :  ,
Last character in string :  g
Second Last character in string :  n
First character in string :  H
Index : Out of range
Index : Out of range

 

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top