Strings & f-strings
Indexing and slicing, everyday string methods, split/join, Unicode and powerful f-string formatting.
Text is the most common kind of data you'll handle: names, messages, file contents, web pages, JSON. Python's str type is powerful and pleasant to use. In this lesson you'll learn to create, slice, search, transform and format strings — and master f-strings, the modern way to build text.
Creating strings#
Single and double quotes are identical; pick one style and use the other when your text contains quotes:
A backslash starts an escape sequence. When you want backslashes kept literally — Windows paths, regular expressions — use a raw string with an r prefix:
Indexing and slicing#
A string is a sequence of characters, numbered from 0. Negative indexes count from the end:
A slice s[start:stop:step] extracts a piece. start is included, stop is excluded, and any part can be omitted:
Indexing past the end raises IndexError, but slicing never does — s[5:100] simply returns what's there.
Strings are immutable#
You can't change a string in place. s[0] = "e" raises TypeError. Every string method returns a new string, so remember to keep the result:
The methods you'll use every day#
Cleaning and checking:
Splitting and joining
split() breaks a string into a list; join() glues a list of strings back together. They're opposites and you'll use them constantly:
Note that join is called on the separator, and every item must already be a string: ", ".join(str(n) for n in [1, 2, 3]).
f-strings: formatting done right#
An f-string (formatted string literal) starts with f and evaluates any expression inside {}:
Add a format spec after a colon to control how the value is displayed:
Aligned columns make tidy reports:
Two more tricks. The = specifier prints the expression and its value — perfect for debugging — and !r shows the repr() (with quotes):
Since Python 3.12, f-strings can even reuse the same quote type inside the braces (f"{", ".join(names)}"), although mixing quote styles remains more readable.
You may still see older styles in existing code: "Hi %s" % name and "Hi {}".format(name). They work, but prefer f-strings in new code.
Unicode: text is more than ASCII#
Python 3 strings are Unicode, so any language and emoji just works:
len counts code points, which is why the Hindi word counts as 6 (some visible letters are made of two code points). When you read and write files, always say encoding="utf-8" — you'll see that in the files lesson.
Worked example: a username generator#
Common mistakes#
- Forgetting the
f:"Hi {name}"prints the braces literally. - Discarding method results:
s.strip()alone does nothing useful; writes = s.strip(). - Concatenating non-strings:
"Total: " + 5fails; use an f-string. - Building big strings with
+=in a loop: collect pieces in a list and"".join(pieces)at the end — it's clearer and faster. - Off-by-one slices: remember the stop index is excluded.
What's next#
Now that you can shape text, let's make programs interactive: the next lesson covers input and output — reading from the keyboard, printing nicely and handling command-line arguments.
Check your understanding
Quick quiz
1.Given
s = "Elephantoo", what iss[1:4]?2.What happens when you run
name = "ada"thenname.upper()and printname?3.Which f-string prints
Total: 42.50(the number right-aligned in 8 characters with 2 decimals)?
Finished reading?
Mark this lesson complete to track your progress.