String is a sequence

A string is a sequence of characters. A word for example “hello” is string and is sequence of characters h, e, l, l and o. Python gives us the ability to access the characters one at the time.
>>> word = ‘hello’
>>>letter = word[1]
>>>print letter
e
In previous example the second statement extracts the character at index position 1 from the word variable and assigns it to letter variable. The expression in brackets is called an index. The index indicates which character in the sequence you want.
If you check out result of the previous code you might not get what you expect. You thought that first letter of ‘hello’ is h not e. But in Python, the index is an offset from the beginning of the string, and the offset of the first letter is zero.
So h is the 0th letter of hello , e is the 1th letter, and n is 2th letter.
h
e
l
l
O
[0]
[1]
[2]
[3]
[4]

You can use any expression, including variables and operators, as an index, but the value of index has to be an integer. Otherwise you get:
>>> letter = word[3.28]
TypeError: string indices must be integers. 

Nema komentara:

Objavi komentar