Strings and formatting
Treat text as an immutable sequence and build clear messages from program values.
By the end, you’ll be able to…
- Index and slice text using zero-based, end-exclusive positions.
- Clean and combine strings without assuming methods change the original.
- Use f-strings to interpolate and format values.
01Text has positions and boundaries
A string is a sequence of Unicode code points. For ordinary text examples, think of it as an ordered row of characters, each addressable by position. The first index is zero, and -1 selects the final item. len reports the sequence length. Some visible symbols, such as an accented character built from multiple code points, can occupy more than one position; a string index is not always a complete visible symbol.
A slice selects a span: text[start:stop] includes start but excludes stop. Imagine boundaries between the items rather than counting the final item twice. Omitting start means the beginning; omitting stop means the end. A single out-of-range index raises IndexError, while a slice can safely extend beyond the sequence. Check a slice by predicting how many positions it spans.
02Cleaning creates a new string
Strings are immutable: an existing string's contents cannot be changed. Methods such as strip, lower, and replace return string results. A method is an operation reached through an object using a dot. raw.strip() asks the string referred to by raw for a version without leading and trailing whitespace. Assign that result if you want to use it later.
strip does not remove spaces in the middle, and lower is a transformation rather than a guarantee that text is valid. Decide what cleanup your application intends. For example, lowercasing a category label can help compare categories consistently, but rewriting someone's name without a reason can lose their preferred presentation. Inspect both the original and cleaned value when developing a cleanup step.
03Build messages with f-strings
An f-string begins with f before its quote. Expressions inside braces are evaluated and incorporated into the resulting text. This keeps the sentence readable while allowing values to vary. Unlike joining a string directly to an integer with +, interpolation handles producing a textual representation of the value. The braces contain Python expressions; the surrounding text remains a message.
A colon inside braces introduces a format specification. The .2f specification displays a number with two digits after the decimal point. Formatting changes the representation for a reader, not the original numeric value. For a receipt, this distinction matters: you can display a tidy amount while retaining a separate numeric total for subsequent work. Do not parse a formatted message back into numbers to continue a calculation.
04Split and join at deliberate boundaries
split turns a string into a list of pieces; the next lesson examines lists closely. With no argument, split separates on whitespace and groups repeated whitespace together. With an explicit separator such as a comma, the separation follows that exact delimiter instead. This simple operation is useful for controlled text, but real CSV files can contain quoted delimiters and require the csv module later in the course.
join goes in the other direction: call it on the separator string and provide the pieces. The separator is placed between pieces, so it does not automatically add punctuation at the start or end. Each piece must be a string. As a self-check, predict whether replacing the separator with ' / ' changes the pieces themselves or only the newly constructed output.
The ideas worth keeping.
- Indices select items; slices select spans with an excluded stop boundary.
- String methods produce results, so store the result you need.
- f-strings combine readable text with values and explicit display formatting.
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.
Build a clean course label
Given title = ' Learn Python ', create the label learn-python and print it. Then print the original with repr to show it still contains its surrounding spaces.
Explore a worked solution
title = " Learn Python "label = title.strip().lower().replace(" ", "-")print(label)print(repr(title))The transformations return strings that can be chained. Binding label to the result leaves title referring to its original text.
Format a travel summary
Given city = 'Pune', distance = 125.678, and ticket = 'PN-204', print Pune: 125.68 km and then the numeric ticket suffix 204 using a slice.
Explore a worked solution
city = "Pune"distance = 125.678ticket = "PN-204"print(f"{city}: {distance:.2f} km")print(ticket[3:])The format specification controls the displayed precision. The prefix occupies positions 0 through 2, so the end slice starts at index 3.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
Build a clean course label
Given title = ' Learn Python ', create the label learn-python and print it. Then print the original with repr to show it still contains its surrounding spaces.
title.strip().lower().replace(" ", "-")
repr(title)Keep exploring.
The official references behind this chapter, when you want a second angle or the full details.
One chapter closer.
Reading is a start. Trying it yourself makes the connection.