Indexes and slices

Accessing characters, slices and string length.

A string is a sequence of characters. Every character has a number, its index, and counting starts at zero. Negative indexes count from the end: -1 is the last character.

word = "Python"
print(word[0])    # P
print(word[-1])   # n
print(len(word))  # 6

An index beyond the string gives IndexError. The last character is word[len(word) - 1], or more simply word[-1].

The slice word[start:stop] returns a piece of the string: from start inclusive to stop exclusive. Either bound can be left out, and a third parameter sets the step:

print(word[0:2])   # Py
print(word[2:])    # thon
print(word[:-1])   # Pytho
print(word[::-1])  # nohtyP

A slice with a step of -1 walks the string from the end and reverses it.

Why is stop not included? That way the length of a slice equals stop - start, and word[:2] + word[2:] always gives back the original string. Unlike an index, a slice past the bounds does not fail, it just returns what is there.

Strings are immutable. word[0] = "J" gives a TypeError: characters cannot be changed in place. Instead you build a new string: "J" + word[1:]. Concatenation is +, repetition is *: "ab" * 3 gives ababab.

The in operator checks whether a substring is present: "th" in word is True. Long text is written in triple quotes """...""", and then line breaks are kept as they are. A line break inside ordinary quotes is written as \n.

Practice

  1. A slice

    What does the program print?

    word = "Python"
    print(word[1:4])
    
  2. Replacing a character

    What happens when you run s = "cat" and then s[0] = "b"?

    • A TypeError
    • s becomes bat
    • s becomes bcat
    • Nothing changes, and there is no error
  3. First and last

    Write a function first_last(word) that returns a string made of the first and the last character of the word. For a one-letter word that letter is repeated twice.