Indexing in String

This topic covers introduction of indexing in string.

Indexing in Strings

Index represent the position number of each character in a string
They are written in square braces []
Using index number in square braces, we refer to specific character in a string
Index number starts with zero 0
The first character of a string will have index number 0

str[0] refers to first character, str[1] refers to second character in a string and so on

Positive Index012345
Negative Index-6-5-4-3-2-1

Above table represent positive and negative index number for string PYTHON.

When index is represented in a negative number, it represent character in a reverse order
Index number [-1] refers to last element or character in a string
Index number [-2] refers to second last character in a string

Code : Creating a string ‘PYTHON and displaying first and last character using index number

Assign a string ‘PYTHON’ to a variable

str =  'PYTHON'

Displaying first and last character of a string using index its position

str = 'PYTHON'
print('First Character:',str[0])
print('Last Character:',str[-1])


First Character: P
Last Character: N


Leave a Comment

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s