Loops, and where your data lives

INPUT · Slides

Cutting out a piece

01 / 07

Cut out a range

When you want several characters at once rather than one, you slice.

Write word[0:3] and you get from number 0 up to but not including number 3 — the first three characters. Exactly the shape you used on lists.

word = "sunday"print(word[0:3])

Result

sun

02 / 07

The end number is left out

Here is the part that catches people. Number 3 is not in [0:3].

lettersunday
index012345

What you get is 0, 1 and 2 — three characters. Settle on "the far number is not included" and be done with it. It is what lets you read [0:3] as "three characters worth".

word = "sunday"print(word[3:6])

Result

day

03 / 07

The numbers can be left off

Leave the front one off and it means "from the start"; leave the back one off and it means "to the end".

  • word[:3] … three characters from the start
  • word[3:] … from the fourth character to the end
  • word[:] … the whole thing

The shortened forms are the ones you will see most. Do not count what you do not have to count — that is the trick.

word = "sunday"print(word[:3])print(word[3:])print(word[:])

Result

sun
day
sunday

04 / 07

Minus works in a slice too

Minus numbers are allowed inside a slice. [-2:] is "the last two characters", [:-1] is "everything but the last one".

You can cut the ends off without looking up the length, so these two come up constantly.

word = "sunday"print(word[-2:])print(word[:-1])

Result

ay
sunda

05 / 07

The image of slicing a list

Put them side by side. The writing is identical and only what comes back differs.

  • Slice a list and you get a list
  • Slice a string and you get a string

Python is built so that "things in a row" answer to the same symbols. Learn it once and it works on both.

fruits = ["apple", "orange", "grape"]word = "sunday"print(fruits[0:2])print(word[0:2])

Result

['apple', 'orange']
su

06 / 07

A string cannot be written over

And here is one big difference. A list let you swap an item out with fruits[0] = "peach".

A string will not have it. Try to put one character in place of another and you are stopped with an error.

word = "cat"word[0] = "b"

Result

TypeError: 'str' object does not support item assignment

07 / 07

To change one, build a new one

So what do you do when you want one character different? Rather than alter the original, make a new string.

Cut and join, and that is it. The old word is still sitting there untouched, and a separate string has come into being.

This "the original never changes" behaviour turns up again next lesson. Every tool for working on strings hands back a new string.

word = "cat"new_word = "b" + word[1:]print(new_word)print(word)

Result

bat
cat