Sunday 15 September 2019

String and Index number in Python

Python - String and Index number

Strings can be used in Python using index (subscript).

Each character of a String is assigned an index number from left to right starting with number 0. For example, for a string “Python”, the index numbers are:


 +-----------------------+
 | P | y | t | h | o | n |
 +-----------------------+
   0   1   2   3   4   5  

0 to 5 are respective index number assigned to individual character of a string Python.

 +-----------------------+
 | P | y | t | h | o | n |
 +-----------------------+
  -6  -5  -4  -3  -2  -1  

-1 to -6 are the corresponding negative indices of a string “Python”.

The first character of a string is indexed as 0. Observe the following examples to understand string index numbers:

>>> str = 'PythonPracticals'

# prints character at position 0
>>> str[0]  
'P'

# prints character at position 1
>>> str[1]  
'y'

# prints character at position 2
>>> str[2]  
't'

# prints character at position 5
>>> str[5]
'n'

In Python string, index may also have negative numbers. To refer string from the end to first character of a string, negative index is useful. Check the following examples:


>>> str = 'PythonPracticals'

# prints last character
>>> str[-1]  
's'

# prints second-last character
>>> str[-2]
'l'

# third character from end of string
>>> str[-3]
'a'

Note that since -0 is considered as 0, negative index starts with -1 value.


No comments:

Post a Comment