String slicing and the text toolkit
Use negative indices, stepped slices, escape sequences, and the string methods that everyday text work depends on.
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.
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.
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.
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.
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.
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.
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.
Explore a worked solution
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.
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.
Explore a worked solution
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.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
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.
text.count(" ")
text.replace(" ", " ")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.