LESSON 07 · BEGINNER4 min read

String slicing and the text toolkit

Use negative indices, stepped slices, escape sequences, and the string methods that everyday text work depends on.

Python 3.12+Free to readModule 2 of 19
YOUR NEXT SMALL WINS

By the end, you’ll be able to…

  • Index text from either end and predict IndexError boundaries.
  • Slice with start, stop, and step, including omitted bounds.
  • Represent newlines, tabs, quotes, and backslashes correctly.
  • Choose among search, count, replace, and case methods.

01Every character has two addresses

A string is an ordered sequence. Positive indices count from zero at the left; negative indices count from -1 at the right. Both address the same character, so word[0] and word[-len(word)] are equivalent. Asking for an index outside the sequence raises IndexError.

Indexing returns one character, which is itself a one-character string. This is different from slicing, which returns a new string even when the slice contains one item. Keep the distinction in mind when a function expects a string and you are tempted to pass a number.

string_addresses.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

02Slices have start, stop, and step

The slice text[start:stop:step] includes start, excludes stop, and advances by step. Omitting start begins at the left edge; omitting stop continues to the right edge. A negative step walks backward, which is why text[::-1] reverses a string. A step of zero raises ValueError.

Slices are forgiving at the edges: text[3:99] simply returns everything from position 3 onward. That makes slices useful for parsing prefixes and suffixes, but it also means an off-by-one mistake may produce a plausible result instead of an error. Predict the number of selected positions before running the code.

slice_drill.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

03Escape sequences represent one character

A backslash introduces an escape sequence. The two characters \n become one newline character, \t becomes a tab, and \\ becomes a literal backslash. Quotes can be escaped when the same quote delimits the string. The escape is part of the source representation, not two visible characters in the resulting value.

Use repr when you need to see the exact representation of a string. A raw string, written with r before the quote, keeps backslashes literal; it is useful for Windows paths and regular-expression patterns. A triple-quoted string is convenient for multiline text but still processes ordinary escapes unless it is also raw.

escapes.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

04The everyday text toolkit

Search and inspect with startswith, endswith, count, and find. find returns -1 when the substring is absent, while index raises ValueError. Use the one whose failure behavior matches your program: a missing optional marker may deserve -1, while a required delimiter should stop the calculation.

Transformations return new strings. replace changes every occurrence unless you pass a count; capitalize uppercases the first character and lowercases the rest; title capitalizes each word; strip removes leading and trailing whitespace. Case-sensitive methods do not guess what you meant, so normalize deliberately when comparing user input.

text_toolkit.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
LET IT CLICK

The ideas worth keeping.

  • Positive and negative indices address the same sequence from opposite ends.
  • Slices take a start, an excluded stop, and an optional step.
  • Escape sequences produce single characters; string methods return new strings.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

Make it yours.

Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.

01

Detect and repair double spaces

Given text = 'Python is fast and clear', count how many double spaces it contains, replace each double space with a single space, and print both the count and the cleaned text.

your_turn_1.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.pyPython
text = "Python  is  fast  and  clear"double_spaces = text.count("  ")cleaned = text.replace("  ", " ")print(double_spaces)print(cleaned)

count reports three occurrences. One replace call fixes all of them because replace changes every occurrence by default. For arbitrary runs of whitespace, a regular expression or split/join is more robust.

02

Fill a letter template

Print a three-line letter for Ada that includes the course name Python and the date 2026-10-22. Use an f-string and escape sequences rather than three separate print calls.

your_turn_2.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.pyPython
name = "Ada"course = "Python"date = "2026-10-22"letter = f"Dear {name},\nYou are selected for the {course} track.\nDate: {date}"print(letter)

The f-string evaluates the names and the escape sequences create the line breaks. Keeping the template in one string makes it easier to reuse with different values.

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 3 answered
01What is 'amazing'[1:6:2]?
02What does 'hello'.find('z') return?
03After name = ' Ada '; name.strip(), what does name contain?
⚡CODING CHALLENGE
🔒Required to Mark Lesson Complete

Detect and repair double spaces

Given text = 'Python is fast and clear', count how many double spaces it contains, replace each double space with a single space, and print both the count and the cleaned text.

EXPECTED OUTPUT
text.count("  ")
text.replace("  ", " ")
main.pyPython 3
Ctrl + ↵
Execution Console
Click "Run & Verify" (or press Ctrl + Enter) to test your code against the challenge.

Keep exploring.

The official references behind this lesson, when you want a second angle or the full details.

One lesson closer.

Reading is a start. Trying it yourself makes the connection.

Solve the hands-on coding challenge in the knowledge section to verify your code and unlock lesson completion.