Strings
Working with text
In this lesson
Explain it like I’m 5
A string is a row of characters in a fixed order — like beads on a thread. You can read any bead by its position and make new threads, but you can’t swap a bead in place.
Quotes, escaping, and multi-line text
Use single or double quotes — pick one and be consistent. To include the same quote inside, either use the other kind ("it's fine") or escape it with a backslash ('it\'s fine'). \n means a new line. Triple quotes ("""...""") let a string span several lines.
print('it\'s fine')
print("line 1\nline 2")
it's fine line 1 line 2
Joining text: + and f-strings
You can join strings with + ("Py" + "thon" → "Python"), but the cleaner way to mix text and values is an f-string: put f before the quote and drop variables into braces — f"Hi, {name}!". f-strings get their own lesson later; they’re worth getting comfortable with.
greeting = "Py" + "thon"
name = "Ada"
print(greeting)
print(f"Hi, {name}! Welcome to {greeting}.")
Python Hi, Ada! Welcome to Python.
Indexing and slicing
Characters have positions starting at 0. word[0] is the first character; word[-1] is the last. A slice grabs a range: word[0:3] takes positions 0, 1, 2 (the end is excluded). Slicing always makes a new string.
word = "Python"
print(word[0], word[-1])
print(word[0:3])
print(len(word))
P n Pyt 6
Methods, and immutability
Strings come with handy methods: .upper(), .lower(), .strip() (remove surrounding spaces), .replace(a, b), and .split(). These all return a new string — the original never changes, because strings are immutable. So you must capture the result: name = name.strip().
name = " Ada Lovelace "
print(name.strip())
print(name.strip().upper())
print(name.strip().split())
Ada Lovelace ADA LOVELACE ['Ada', 'Lovelace']
Take the messy name below, strip the spaces, and print it in uppercase. Bonus: print just the first character.
name = " grace hopper "
print(name.strip().title())
Chain methods: .strip() then .title(). Index with [0] for the first letter.
name = " grace hopper "
clean = name.strip().title()
print(clean)
print(clean[0])
Grace Hopper
More string methods you’ll reach for
A handful of extra methods come up again and again. .startswith() and .endswith() test the ends of a string; .find() returns the position of some text (or -1 if it’s missing); .count() tallies how many times something appears; and .replace(old, new) swaps text.
Two more are a bridge to lists: .split() breaks a string into a list of pieces, and .join() glues a list back into a string. (When you’re building text from variables, an f-string is usually cleaner than +.)
email = "[email protected]"
print(email.endswith(".com"))
print(email.split("@"))
words = ["learn", "python", "today"]
print("-".join(words))
True ['ada', 'example.com'] learn-python-today
Common mistake: Calling a string method but ignoring the result
Because strings are immutable, methods return a new string instead of changing the original. Writing name.upper() on its own line throws the new value away.
Capture the result: name = name.upper() (or use it directly in a print).
name = "ada"
name = name.upper()
print(name)
What does "hello"[1] return?
Indexing starts at 0, so position 1 is the second character, e.
After s = "hi"; s.upper(), what is s?
Strings are immutable; .upper() returns a new string but leaves s as "hi" unless you reassign it.
Mini exercise (medium)
Given email = " [email protected] ", produce a clean lowercase address with no surrounding spaces and print it.
Do it here. Finish the code below and press Run to try your answer right in the browser — no setup needed.
email = " [email protected] "
clean = email # TODO: strip the spaces and lowercase it
print(clean)
Chain .strip() and .lower().
email = " [email protected] "
clean = email.strip().lower()
print(clean)
[email protected]
__no_output_bypass__ = True
import ast as _ast
_calls = [n.attr for n in _ast.walk(_ast.parse(__user_code__)) if isinstance(n, _ast.Attribute)]
assert "strip" in _calls, "call .strip() to remove the surrounding spaces"
assert "lower" in _calls, "call .lower() to make all letters lowercase"
__no_output_bypass__ = False
assert clean == "[email protected]", "clean should have no surrounding spaces and be lowercase"
print("✓ Clean!")