0%

Working with Text · practice

Take Parts with Slices

retrieves one character. A retrieves a sequence of characters as a new .

word = "planet"
beginning = word[0:3]
print(beginning)

The output is pla.

Start included, stop excluded

A basic slice has two indexes separated by a colon:

text[start:stop]

The start index is included. The stop index is not included.

For word[0:3], Python takes indexes 0, 1, and 2. It stops before index 3.

The string planet is aligned with positive and negative indexes. A slice starts at included index 0, stops before excluded index 3, and returns 'pla'.

This rule may feel unusual at first, but it has useful consequences. The number of characters in word[0:3] is 3 - 0, which is three.

Leave out an endpoint

Leave out the start to slice from the beginning:

print(word[:3])

Leave out the stop to slice through the end:

print(word[3:])

These print pla and net.

You can use negative indexes in slices too:

print(word[-3:])

This takes the final three characters: net.

Slices are forgiving

An individual index outside a string reports . A slice can stop beyond the end without failing:

print(word[:100])

Python returns all available characters. This difference is useful, but you should still choose slice boundaries that communicate your intention.

What will this program print?

text = "notebook"
print(text[4:])

Split a course title

The starter string is:

Python Fundamentals

Use two slices:

  • Python to language;

  • assign Fundamentals to level.

Do not type those finished strings as literal answers. Derive them from course with slice notation.

The output must be:

Language: Python
Level: Fundamentals

Task

the existing course so language becomes Python and level becomes Fundamentals.

Produce:

Language: Python
Level: Fundamentals