Skip to content

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.

PythonPython not started

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.

PythonPython not started

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.

PythonPython not started

This is what immutable means, and it is why text.strip() on its own does nothing useful — you have to keep the result:

PythonPython not started

The methods you will actually use

PythonPython not started

Splitting and joining

These two are the workhorses of text processing.

PythonPython not started

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 {}.

PythonPython not started

Multi-line text

Triple quotes preserve newlines exactly, which makes them the natural home for prompts.

PythonPython not started

Try it yourself

Exercise 1

Print the domain from the email address — just example.com, nothing else.

Your turnPython not started
Exercise 2

Build headline so it reads exactly tuned-v2 scored 88.4% on 1,250 samples.

Your turnPython not started

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.
  • split and join are the pair you will use most.
  • f-strings with format specs (:.2f, :%, :,, :>10) do your formatting for you.