The index of a character is its position in the string. Python strings are indexed starting from zero to the length of the given string - 1. For example, the string Python is indexed as 0,1,2,3,4,5. The 0 is the index or position of the first character, P, in the string Python, and 1, 2, 3, 4, and 5 are the indexes or positions of y, t, h, o, and n, respectively. Below are some ways to get the character(s) from a string by providing the index(es).
# introducing a stringName = 'Python Course'# To get the 1st character of the given stringprint(Name[0])# To get the 2nd character of the given stringprint(Name[1])# To get 7th character of the given stringprint(Name[6])
You can use a negative index starting from the end of a string to get the character of a string, as shown below.
Name = 'Python Course'# To get the last character of the stringprint(Name[-1])# To get the 2nd last characterprint(Name[-2])
In the example below, you can use the same syntax to extract a few characters instead of just one.
Name = 'Python Course'# To get the first three charactersprint(Name[0:3])# To get all the characters startimng from zero indexprint(Name[0:])# To get all the characters starting from zero to the 5th indexprint(Name[:6])# To also get all the characters of the stringprint(Name[:])
When you use the syntax
print(Name[0:])
, Python will assume the indexes from zero to the last index by default. The same applies toprint(Name[:6])
andprint(name[:])
; Python will assume the indexes from zero to the 5th index and from zero to the last index, respectively.