Next / Previous / Contents / TCC Help System / NM Tech homepage

3.2. Indexing strings

To extract one or more characters from a string value, you have to know how positions in a string are numbered.

Here, for example, is a diagram showing all the positions of the string 'ijklm'.

In the diagram above, the numbers show the positions between characters. Position 0 is the position before the first character; position 1 is the position between the first and characters; and so on.

You may also refer to positions relative to the end of a string. Position -1 refers to the position before the last character; -2 is the position before the next-to-last character; and so on.

To extract from a string s the character that occurs just after position n, use an expression of this form:

s[n]

Examples:

>>> stuff = 'ijklm'
>>> stuff[0]
'i'
>>> stuff[1]
'j'
>>> stuff[4]
'm'
>>> stuff [ -1 ]
'm'
>>> stuff [-3]
'k'
>>> stuff[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IndexError: string index out of range

The last example shows what happens when you specify a position after all the characters in the string.