LearnWave
Learn it. Master it.

Strings

Strings and indexing

Access any character of a string by its index.

A string is a sequence of one or more Unicode characters: letters, digits, spaces or symbols. It is written in single, double or triple quotes: 'India', "India" or '''India'''. Triple quotes let a string run over several lines.

Each character has a position number, its index. The first character has index 0, and the last has index n - 1, where n = len(string), the length. For s = 'Namaste India' (13 characters, counting the space), s[0] is 'N' and s[8] is 'I'.

  • An index outside this range gives an IndexError.
  • The index must be an integer: s[1.5] gives a TypeError.
  • It can be an expression, worked out first: s[2 + 4] is the same as s[6].

Negative indices count from the right: -1 is the last character, and -n the first. For s = 'Namaste India', s[-1] is 'a' and s[-13] is 'N'.

Python has no separate character type: a single character is just a string of length 1.

Strings are immutable: once made, they cannot be changed. Trying s[0] = 'M' gives TypeError: 'str' object does not support item assignment. To 'change' a string, you build a new one.

Index 0 to n − 1, or −n to −1.
Index 0 to n − 1, or −n to −1.

Practise this lesson

Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.

No account, no email address. Opens the real product.