Python Foundations·Lesson 3 of 67·beginner
Working with text
Index, slice and transform strings — the type that carries every prompt, response and log line you will ever write.
In this lesson · 14 min
- →Index and slice strings, including negative indices
- →Use the string methods that come up constantly
- →Format values into text with f-strings
- →Understand why strings are immutable
Text is where almost every AI program starts and ends. A prompt is a string, a model’s response is a string, and everything logged in between is a string. It pays to be fluent here.
Strings are sequences
A string is an ordered sequence of characters, numbered from zero.
Negative indices count from the right, so word[-1] is always the last character no matter how
long the string is.
Slicing
s[start:stop] gives you everything from start up to but not including stop.
That “up to but not including” rule looks fussy until you notice it makes
text[:n] and text[n:] fit together perfectly with no overlap and no gap.
Strings never change
Every string operation returns a new string. The original is untouched.
This is what immutable means, and it is why text.strip() on its own does nothing useful —
you have to keep the result:
The methods you will actually use
Splitting and joining
These two are the workhorses of text processing.
Note the direction: separator.join(list_of_strings). It reads backwards the first few times,
but it is the separator that knows how to stitch things together.
f-strings, properly
An f-string evaluates whatever you put inside {}.
Multi-line text
Triple quotes preserve newlines exactly, which makes them the natural home for prompts.
Try it yourself
Print the domain from the email address — just example.com, nothing else.
Build headline so it reads exactly tuned-v2 scored 88.4% on 1,250 samples.
Check yourself
What does "abcdef"[1:4] produce?
Recap
- Strings are zero-indexed sequences; negative indices count from the end.
s[start:stop:step]slices — start inclusive, stop exclusive.- Strings are immutable: every method returns a new string, so keep the result.
splitandjoinare the pair you will use most.- f-strings with format specs (
:.2f,:%,:,,:>10) do your formatting for you.