Strings
Work with text — slicing, methods, and f-string formatting.
- Index and slice strings
- Use common string methods
- Build strings cleanly with f-strings
Text is everywhere — names, messages, file contents, user input. Python's str
type is rich and pleasant to work with once you know the core moves.
Indexing and slicing
A string is a sequence of characters, accessible by position (starting at 0), and
sliceable with [start:stop] (stop is exclusive — the half-open convention
again):
word = "Python"
word[0] # "P"
word[-1] # "n" (negative counts from the end)
word[0:3] # "Pyt"
word[3:] # "hon"Strings are immutable — these operations return new strings; the original is never changed.
Useful methods
Strings come with a toolbox of methods that each return a new string or value:
" hi ".strip() # "hi" (remove surrounding whitespace)
"Hello".lower() # "hello"
"a,b,c".split(",") # ["a", "b", "c"]
"-".join(["a", "b"]) # "a-b"
"hello".replace("l", "L")# "heLLo"
"42".isdigit() # Truef-strings: the way to build text
To insert values into text, use an f-string — prefix the string with f and
put expressions in { }:
name = "Ada"
age = 36
f"{name} is {age}" # "Ada is 36"
f"next year: {age + 1}" # "next year: 37" (any expression works)f-strings are clearer and less error-prone than gluing strings together with +
(and they sidestep the str + int TypeError from the types lesson).
Where to go next
Next: lists and tuples — ordered collections for holding many values.