Strings
Objectives
By the end of this chapter, you should be able to:
- Use common string methods
- Build strings with f-strings
💡 Why this matters: Strings handle almost all text input and output. You’ll use these methods in nearly every program you write.
Strings Are Iterable
A string is a sequence of characters, so you can loop over it like a list:
for x in "word":
print(x)
# w
# o
# r
# d
Strings Are Immutable
You can’t change part of a string in place:
my_str = "can't touch this"
my_str[6] = " " # TypeError
Every string method returns a brand new string. It never modifies the original:
greeting = "hi"
greeting.upper() # 'HI'
greeting # 'hi', unchanged
String Methods
Try each of these in a REPL on "this Is nIce":
| Method | Does | Example |
|---|---|---|
.upper() |
Uppercase everything | "hi".upper() returns 'HI' |
.lower() |
Lowercase everything | "HI".lower() returns 'hi' |
.capitalize() |
Uppercase first letter only | "hi there".capitalize() returns 'Hi there' |
.title() |
Uppercase first letter of every word | "hi there".title() returns 'Hi There' |
.find(x) |
Index of first match, -1 if not found |
"erin".find("e") returns 0 |
.isalpha() |
True if every character is a letter |
"hi".isalpha() returns True |
.endswith(x) |
True if the string ends with x |
"string".endswith("g") returns True |
.find() is case sensitive:
name = "erin"
name.find("e") # 0
name.find("E") # -1, no uppercase "E" in the string
Building Strings with f-strings
Joining variables with + gets messy fast:
first_name = "Jordan"
city = "San Francisco"
greeting = "Hi, my name is " + first_name + ". I live in " + city + "."
An f-string is cleaner. Put an f before the string, then reference any variable directly inside {}:
greeting = f"Hi, my name is {first_name}. I live in {city}."
This is the standard way to build strings in modern Python.
Try It
- Loop over any word, one character at a time, with a
forloop. - Take a string and predict what
.upper(),.capitalize(), and.title()return, then run each to check. - Build a sentence about yourself using an f-string with at least two variables.
Recap
- Strings are iterable and immutable. Methods return a new string rather than modifying the original.
- f-strings (
f"...{variable}...") are the standard way to build strings from variables.
Next lesson: boolean logic, and controlling what your code actually does.