Working With Strings
Create strings, build messages with f-strings, pick out characters with indexes and slices, and clean text with string methods like strip, replace and split.
Welcome back!
Step 1 of 14Learn
Strings: text in quotes
Almost every program handles text: names, emails, messages, file contents. In Python, text is a string (str), written between quotes:
city = "Chicago"
greeting = 'Hello'
note = "It's ready" # double quotes allow an apostrophe inside
poem = """Roses are red,
violets are blue.""" # triple quotes span several linesSingle and double quotes are interchangeable; pick one style and use the other when the text contains that quote character.
Some characters are written with a backslash, called an escape sequence: \n is a new line and \t is a tab. print("Line 1\nLine 2") prints two lines. To include a literal backslash, as in a Windows path, write \\, or put an r before the string to make it "raw": r"C:\Users\ana".
The built-in len() returns the number of characters, spaces included: len("New York") is 8. An empty string, "", has length 0.
Two operators work on strings: + joins (concatenates) them and * repeats them. "ha" * 3 is "hahaha", and "-" * 20 is a quick divider line for console output. But + only joins strings to strings: "Age: " + 30 raises a TypeError. You need "Age: " + str(30) or, much better, an f-string.
Step 2 of 14Learn
f-strings: the easy way to build messages
An f-string is a string with an f before the opening quote. Inside it, anything in curly braces is evaluated and inserted:
name = "Ana"
items = 3
total = 47.5
print(f"{name} bought {items} items for {total} dollars.")
# Ana bought 3 items for 47.5 dollars.No conversions, no plus signs, and the message reads naturally. You can put any expression inside the braces: f"{items * 2} items" or f"{name.upper()}".
After a colon inside the braces you can add a format specification:
f"{total:.2f}"gives47.50: two decimal places, the standard way to show money.f"{1234567:,}"gives1,234,567with thousands separators.f"{0.256:.1%}"gives25.6%: multiplies by 100 and adds the percent sign.f"{name:>10}"right-aligns the text in a 10-character field, handy for tables.
Forgetting the f is the classic mistake: "Hello {name}" prints the braces and the word name literally. If you ever see curly braces in your output, check for the missing f. To print an actual brace in an f-string, double it: f"{{" prints a single {.
Step 3 of 14Practice · Choose one
With qty = 4 and price = 2.5, what does print(f"{qty} x {price:.2f} = {qty * price:.2f}") display?
Step 4 of 14Learn
Indexing: one character at a time
A string is a sequence of characters, and each character has a position called an index. Python counts from 0:
word = "Python"
# P y t h o n
# index 0 1 2 3 4 5
# neg. -6 -5 -4 -3 -2 -1word[0]is"P", the first character.word[5]is"n", the last one, because six characters have indexes 0 to 5.word[-1]is also"n": negative indexes count from the end, which saves you computing the length.word[6]raises anIndexError: there is no seventh character.
Zero-based counting feels odd at first, but it's used by most programming languages, and it makes the arithmetic of slicing (next) work cleanly. The last valid index is always len(s) - 1.
Strings are immutable: you can't change one in place. word[0] = "J" raises a TypeError. Instead, build a new string and reassign the name: word = "J" + word[1:] gives "Jython". Every string operation you'll meet, from slicing to upper(), returns a new string and leaves the original untouched.
Step 5 of 14Compare
Index positions in "Python"
| Aspect | Index from start | Index from end |
|---|---|---|
| P | 0 | -6 |
| y | 1 | -5 |
| t | 2 | -4 |
| h | 3 | -3 |
| o | 4 | -2 |
| n | 5 | -1 |
Step 6 of 14Practice · Fill in the blanks
Fill in the blanks
For word = "Python", word[0] is , word[-1] is , and word[2] is .
Step 7 of 14Learn
Slicing: taking a piece of a string
A slice extracts part of a sequence with [start:stop]. It includes the start index and stops just before the stop index:
s = "spreadsheet"
s[0:6] # "spread" (indexes 0-5)
s[6:11] # "sheet"
s[:6] # "spread" (start defaults to 0)
s[6:] # "sheet" (stop defaults to the end)
s[-5:] # "sheet" (the last five characters)
s[::2] # "sraset" (every second character)
s[::-1] # "teehsdaerps" (reversed)The "stop is excluded" rule is easy to remember with a useful property: the length of s[a:b] is b - a. So s[0:6] has 6 characters, and s[:n] is always the first n characters.
The optional third number is the step: [start:stop:step]. A step of 2 skips every other character, and a step of -1 walks backwards, which is why s[::-1] is the standard way to reverse a string, or to check for a palindrome with s == s[::-1].
Unlike indexing, slicing is forgiving: s[5:100] simply stops at the end instead of raising an error, and a slice whose start is past the end returns an empty string. Slices work the same way on lists, which you'll meet in Module 4.
Step 8 of 14Tap to reveal
Slices of "spreadsheet"
s[0:6]
"spread": indexes 0 to 5; the stop index 6 is not included.s[6:]
"sheet": from index 6 to the end.s[:3]
"spr": the first three characters.s[-5:]
"sheet": the last five characters.s[::-1]
"teehsdaerps": a step of -1 reverses the string.
Step 9 of 14Practice · Choose one
What is "weekend"[2:5]?
Step 10 of 14Learn
String methods: cleaning and transforming text
A method is a function that belongs to a value, called with a dot: text.upper(). Strings have dozens; these cover most needs:
| Method | Example | Result |
|---|---|---|
upper(), lower() | "Ana".upper() | "ANA" |
title() | "ana lee".title() | "Ana Lee" |
strip() | " hi ".strip() | "hi" |
replace(old, new) | "a-b-c".replace("-", "/") | "a/b/c" |
split(sep) | "a,b,c".split(",") | ["a", "b", "c"] |
sep.join(list) | ", ".join(["a", "b"]) | "a, b" |
find(sub) | "banana".find("n") | 2 (or -1 if absent) |
startswith(x) | "INV-77".startswith("INV") | True |
count(sub) | "banana".count("a") | 3 |
The in operator checks for a substring: "@" in email is True or False.
Methods can be chained, each working on the previous result: raw.strip().lower() trims and lowercases in one go. That pattern is common for cleaning user input before comparing it, so that " YES " and "yes" are treated the same.
The number one string bug: calling a method and throwing the result away. Because strings are immutable, name.strip() on its own line does nothing useful; it creates a cleaned string that nobody keeps. Write name = name.strip() to store it.
Step 11 of 14Flashcards
String methods
Tap a card to flip it.
Step 12 of 14Practice · Code challenge · Python
Complete make_username(first, last) so it returns a username made of the first letter of first followed by the whole of last, all in lowercase, with any spaces around the names removed. For example, make_username("Ana", "Lee") returns "alee".
make_username("Ana", "Lee")make_username("maria", "GARCIA")make_username(" Ben", "Ortiz ")
Step 13 of 14Practice · Spot the mistake
This script should print "Hello, Ana Lee!" with no extra spaces. Tap the line that stops it from working as intended.
Step 14 of 14Practice · Match the pairs
Match each expression to its result.
Tap an answer, then tap the place where it belongs (or drag it there).
"data,science,python".split(",")"-".join(["2026", "03", "15"])" Report ".strip()"cat" in "concatenate""hello".find("z")
Lesson complete!