Access Characters

Access Characters

We can access characters of a string by using the following ways.

  1. By using index
  2. By using slice operator
1. Access Characters By using Index
  • Python supports both +ve and -ve Index.
  • +ve Index means Left to Right (Forward Direction)
  • -ve Index means Right to Left (Backward Direction)

E.g

>>> s = 'Waytoeasylearn'
>>> s[0]
'W'
>>> s[4]
'o'
>>> s[-1]
n 
>>> s[20]
IndexError: string index out of range

Note

If we are trying to access characters of a string with out of range index then we will get error saying: IndexError

E.g

s=input("Enter Some String:")
i=0
for x in s: 
    print("The character present at positive index {} and at negative index {} is {}".format(i,i-len(s),x)) 
    i=i+1

Output

Enter Some String:ashok
The character present at positive index 0 and at negative index -5 is a
The character present at positive index 1 and at negative index -4 is s 
The character present at positive index 2 and at negative index -3 is h 
The character present at positive index 3 and at negative index -2 is o 
The character present at positive index 4 and at negative index -1 is k
2. Access Characters by using Slice Operator

Syntax

s[beginindex:endindex:step]
  • Begin Index: From where we have to consider slice (substring)
  • End Index: We have to terminate the slice (substring) at endindex-1
  • Step: Incremented Value.

Note

  • If we are not specifying begin index then it will consider from beginning of the string.
  • If we are not specifying end index then it will consider up to end of the string.
  • The default value for step is 1.
>>> s="Learning Python is very very easy!!!" 
>>> s[1:7:1] 
'earnin' 
>>> s[1:7] 
'earnin' 
>>> s[1:7:2] 
'eri'
>>> s[:7] 
'Learnin' 
>>> s[7:] 
'g Python is very very easy!!!' 
>>> s[::] 
'Learning Python is very very easy!!!' 
>>> s[:] 
'Learning Python is very very easy!!!'
>>> s[::-1]
'!!!ysae yrev yrev si nohtyP gninraeL'
Behavior of Slice Operator
  1. s[begin:end:step]
  2. Step value can be either +ve or –ve
  3. If +ve then it should be forward direction (left to right) and we have to consider begin to end-1
  4. If -ve then it should be backward direction (right to left) and we have to consider begin to end+1.

Note

  • In the backward direction if end value is -1 then result is always empty.
  • In the forward direction if end value is 0 then result is always empty.

In Forward Direction

  • default value for begin 0
  • default value for end: length of string
  • default value for step: +1

In Backward Direction

  • default value for begin: -1
  • default value for end: -(length of string+1)

Note

  • Either forward or backward direction, we can take both +ve and -ve values for begin and end index.
  • Slice operator never raises IndexError

Access Characters
Scroll to top