7: Strings#
What are strings and why should we care about them?#
Strings are everywhere#
We need to learn to work with strings because a lot of data we want to do things with live in the world as mixed data
Email addresses
Webpage URLs
Names
Documents, words
Sales records
Etc.
Strings are the ultimate “lingua franca” between systems
Data is often passed as “serialized” forms (e.g., JSON: Javascript Object Notation)
We assume strings coming in, and we parse it appropriately. This can include data (numbers/records), as we see in one of the Projects for this module!
This also includes the “human system” (i.e., the user)!
Let’s see what comes back from the input() function we introduced in Iteration.
1age = input('What is your age?')
Note: input() requires interactive input. If you run this in your own Python environment, you’ll be prompted to type your age.
If you type 37, the value stored in age is the string '37', not the integer 37:
1age
'37'
What data type is in age?
Strings are sequences of characters#
But what is a string? It’s fundamentally a sequence of characters.
And that’s exactly what a string is in Python too: it’s a sequence of characters, much like (though not exactly like) a list. This means we can iterate through a string in a similar way that we can iterate through any other list.
1s = "banana"
2for char in s:
3 print(char)
b
a
n
a
n
a
1sentence = "she sells seashells by the seashore, except when she doesn't want to sell seashells"
2for char in sentence:
3 print(char)
s
h
e
s
e
l
l
s
s
e
a
s
h
e
l
l
s
b
y
t
h
e
s
e
a
s
h
o
r
e
,
e
x
c
e
p
t
w
h
e
n
s
h
e
d
o
e
s
n
'
t
w
a
n
t
t
o
s
e
l
l
s
e
a
s
h
e
l
l
s
Characters don’t have to be visible/letters!#
Notice that even the “blank space” is a character! A string that includes an empty space character is NOT the same as an empty string (i.e., a list of characters of length zero), even though they print out the same. This distinction is very important to remember as you work with real world data.
1a = "" # a blank/empty string
2b = " " # a string with one blank space *character*
3print("Printing out the value of a")
4print(a)
5print("Printing out the value of b")
6print(b)
7print(len(a), len(b))
8print(a == b)
Printing out the value of a
Printing out the value of b
0 1
False
This means that whitespace at the beginning or end of strings define completely different strings! For example:
1a = "James"
2b = " James"
3c = "James "
4print(a == b)
5print(b == c)
6print(a == c)
False
False
False
1clean = ""
2for char in b:
3 if char != " ":
4 clean = clean + char
5clean
'James'
Other kinds of characters that don’t look like “letters”:
\tfor tabs\nfor newlines
1# tab is \t
2s = "a\ttab\nand a newline"
3print(s)
4for i in range(len(s)):
5 print(i, s[i])
a tab
and a newline
0 a
1
2 t
3 a
4 b
5
6 a
7 n
8 d
9
10 a
11
12 n
13 e
14 w
15 l
16 i
17 n
18 e
Again, even though they may look similar to our eyes (“blank”), they are not the same!
1a = " "
2b = "\t"
3c = "\n"
4print("a is ", a, "with length", len(a))
5print("b is ", b, "with length", len(b))
6print("c is ", c, "with length", len(c))
7print("is a the same as b?", a == b)
8print("is b the same as c?", b == c)
9print("is a the same as c?", a == c)
a is with length 1
b is with length 1
c is
with length 1
is a the same as b? False
is b the same as c? False
is a the same as c? False
We’ll see in the next module how text data often comes in with a mix of various whitespace characters, which we can use to parse the data into structured records.
For example, the following string may look ridiculous, but the \t and \n characters in the string actually break it up quite nicely into a structured format that is readable by both humans and Python.
1records = "NAME\tSCORE\tGRADE\nJoel\t81\tB-\nRony\t98\tA+\nSravya\t99\tA+"
2print(records)
NAME SCORE GRADE
Joel 81 B-
Rony 98 A+
Sravya 99 A+
Properties of strings#
Like lists, strings are sequences: ordered collections of items that support indexing, slicing, len(), and the in operator. But strings are not lists — you can’t use list methods like .append() on a string. And there is one other important difference: strings are immutable. You can never modify a string directly, only create a new string that you must then assign to a variable (or reassign to the same variable) if you want to preserve that change. More on this when we talk about working with strings.
Strings are ordered (and therefore can be sorted and indexed and sliced like lists)#
1a_string = "hello world Hi"
2print(sorted(a_string))
[' ', ' ', 'H', 'd', 'e', 'h', 'i', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
1# can be indexed
2a_string[0]
'h'
1# and sliced
2a_string[:5]
'hello'
Strings have length#
1# has length
2print(len(a_string))
14
Strings are IMMUTABLE (you can’t modify them directly)#
1a_string = "hello"
2a_string.upper() # this does NOT change a_string
3print(a_string) # still "hello"
4
5# to preserve the change, you must reassign
6a_string = a_string.upper()
7print(a_string) # now "HELLO"
hello
HELLO
This property of strings has one critical implication for how you work with them (vs. other data types): anytime you modify a string, you must have some kind of variable assignment statement (even if it is back to itself) to preserve the change.
This is a really important point we’ll drive home later when we dig into ways of working with strings.
Aside: string encoding#
The previous observation about blank spaces illustrates a larger point: we deliberately say strings are sequences of characters, not letters. This is because strings can include numbers, as we’ve seen (think usernames like joelchan86, or your uids), but also all sorts of other characters, including various kinds of blank spaces — like tabs, spaces, and newlines — and even emoji!
Check this resource for an overview and initial guide: https://realpython.com/python-encodings-guide/
This is something I want to show you to give you a better intuition for what strings are, but there is also an important practical implication: you need to be very careful to transform or normalize your strings when you want to sort or compare them. What’s the same or different to your human eye will often not be the same or different to the computer’s eye.
For example, “A” and “a” have different encodings. We can use the built-in ord() function to see the numeric code for any character:
1# each character has a unique numeric code
2print("A:", ord("A"))
3print("a:", ord("a"))
4print("B:", ord("B"))
5print("0:", ord("0"))
6print(" :", ord(" "))
A: 65
a: 97
B: 66
0: 48
: 32
Notice that 'A' is 65 and 'a' is 97 — completely different numbers! This is why Python does not see them as the same “letter”. Similarly, a space character has its own code (32), which is why "James" and "James " are different strings:
1s1 = "James"
2s2 = "james"
3s3 = "James "
4print(s1 == s2) # False - different case
5print(s1 == s3) # False - trailing space
False
False
Working with strings: basics#
Similar to lists, many basic operations with strings revolve around indexing and iteration.
Getting parts of a string#
Indexing#
Works similarly to lists.
1s = "my name is inigo montoya, you killed my father, prepare to die!"
2for i in range(len(s)):
3 char = s[i]
4 print(i, char)
0 m
1 y
2
3 n
4 a
5 m
6 e
7
8 i
9 s
10
11 i
12 n
13 i
14 g
15 o
16
17 m
18 o
19 n
20 t
21 o
22 y
23 a
24 ,
25
26 y
27 o
28 u
29
30 k
31 i
32 l
33 l
34 e
35 d
36
37 m
38 y
39
40 f
41 a
42 t
43 h
44 e
45 r
46 ,
47
48 p
49 r
50 e
51 p
52 a
53 r
54 e
55
56 t
57 o
58
59 d
60 i
61 e
62 !
1s = "my name is inigo montoya, you killed my father, prepare to die!"
2for char in s:
3 print(char)
m
y
n
a
m
e
i
s
i
n
i
g
o
m
o
n
t
o
y
a
,
y
o
u
k
i
l
l
e
d
m
y
f
a
t
h
e
r
,
p
r
e
p
a
r
e
t
o
d
i
e
!
1s = "my name is inigo montoya, you killed my father, prepare to die!"
2# give me the last letter
3print(s[-1])
!
Just like with lists, negative indexing works too — -1 gives you the last item, -2 gives the second-to-last, and so on.
PRACTICE: How would you get the first number of the level (after the four-letter code)?
1code = "INST201"
2# your code here
Answer:
1print(code[4]) # '2'
The department INST takes up indices 0 through 3, so the first number is at index 4.
PRACTICE: How would you get the first initial for each name?
1names = ["Joel", "Sarah", "John", "Michael", "Patrick", "Kacie"]
2# your code here
Answer:
1for name in names:
2 print(name[0])
Each name is a string, so name[0] is its first character. This is the same as indexing into a list, just one level down: first we loop over the list to get each string, then we index into the string.
Slicing#
Remember slicing? Here we can think about substrings. Super useful for truncation, or getting particular parts of strings when you know the pattern (e.g., first four characters of a course code is always the department).
Remember: the index before the : indicates where you want to start, and the index after the : indicates where you want to stop before. So [0:4] will go from index 0 to index 3 (before index 4). Leaving out an index implicitly says “to the max” (e.g., from 0 or until the end).
1code = "INST201"
2# get the first four chars (index 0 to 3, stop before 4)
3area = code[:4]
4print(area)
INST
PRACTICE: how would you get the course number?
1# get last three characters
2code = "INST201"
3# your code here
Answer:
1print(code[4:]) # '201'
Start at index 4 (right after the department) and leave out the stop to go to the end. code[-3:] (the last three characters) also works here.
PRACTICE: How would you get the first 2 letters of the name?
1name = "Michelle"
2# your code here
Answer:
1print(name[:2]) # 'Mi'
When you start from the beginning, the stop number is the same as how many characters you get.
We can put these into filtering/counting patterns that check parts of strings!#
PRACTICE: How many students in the class have names that begin with Eli?
1names = [
2 "Eliana",
3 "John",
4 "Elias",
5 "Esther",
6 "Joseph",
7 "Ebenezer",
8 "Eric",
9 "Josiah",
10 "Joe",
11 "Eliza",
12 "Frank",
13 "Ellie",
14]
15
16count = 0
17
18for name in names:
19 if name[:3] == "Eli": # fill in your boolean expression
20 count += 1
21
22count
3
PRACTICE: What about grabbing the names that begin with Jo?
1names = [
2 "Eliana",
3 "John",
4 "Elias",
5 "Esther",
6 "Joseph",
7 "Ebenezer",
8 "Eric",
9 "Josiah",
10 "Joe",
11 "Eliza",
12 "Frank",
13 "Ellie",
14]
15
16target_names = []
17
18# your code here
Answer:
1for name in names:
2 if name[:2] == "Jo":
3 target_names.append(name)
4target_names # ['John', 'Joseph', 'Josiah', 'Joe']
This is the same filtering pattern as the Eli example, but we .append() the matching names instead of counting them. Notice the slice is [:2] this time, since "Jo" is 2 characters long.
Join strings#
We’ve also already shown you concatenation.
1s1 = "Hello"
2s2 = " World!"
3print(s1 + s2)
Hello World!
Now that you’ve seen lists, you can get a bit more intuition for how it works.
1l1 = [1, 2, 3]
2l2 = [4, 5, 6]
3print(l1 + l2)
[1, 2, 3, 4, 5, 6]
Check if character(s) is in string#
Just like lists, the in operator also works for strings. We can think of this as checking whether some substring (could be a single character, or a sequence of characters) is part of a target string.
Example: check whether this message contains a keyword
1message = "hello, my name is inigo montoya"
2keyword = "ingo"
3# let's check if the message mentions my name!
4print(keyword in message)
False
PRACTICE: check whether these strings contain a space or tab!
tab is represented by '\t'
space is represented by ' '
1s1 = "\tInigo"
2s2 = " Inigo"
3# your code
Answer:
1print("\t" in s1) # True
2print(" " in s1) # False
3print("\t" in s2) # False
4print(" " in s2) # True
Both strings look like they start with a blank, but s1 starts with a tab and s2 starts with a space. To Python, those are different characters.
Put it into our filtering pattern!#
PRACTICE: Only grab the classes from CMSC
1course_codes = ["INST201", "INST126", "INFM322", "CMSC126"]
2
3target_courses = []
4
5# your code
Answer:
1for code in course_codes:
2 if "CMSC" in code:
3 target_courses.append(code)
4target_courses # ['CMSC126']
Our filtering pattern again, with in as the Boolean expression.
PRACTICE: Only grab the emails that are from .edu domain
1emails = ["oasislab@gmail.com", "joelchan@terpmail.umd.edu", "rony@terpmail.com", "joelchan@umd.edu", "joelchan@gmail.com", "sarahp@umd.edu", "sarah@umd.org"]
2target_emails = []
3
4# your code here
Answer:
1for email in emails:
2 if ".edu" in email:
3 target_emails.append(email)
4target_emails # ['joelchan@terpmail.umd.edu', 'joelchan@umd.edu', 'sarahp@umd.edu']
This works for these emails, but in checks for ".edu" anywhere in the string. So it would also grab an email like "joe.education@gmail.com"! There’s a more precise way to check this (.endswith()): more on that when we get to string methods.
Practice: Indexing, slicing, and checking parts of strings#
Let’s practice these basics a couple of ways. First, we’ll READ code and predict what it does (code tracing). Then we’ll flip it around and WRITE the code ourselves from an English description.
Part 1: Code tracing#
Predict the output of each code snippet before running the cell!
Trace 1#
1code = "INST126"
2print(code[0])
3print(code[-1])
A)
Ithen6B)
Nthen6C)
Ithen2D)
INSTthen126
Answer:
A) I then 6
Just like lists, index 0 is the first character and index -1 is the last character. If you picked B, you’re thinking of index 0 as the “second” item. If you picked D, you’re thinking of the “parts” of the code that matter to us (department and number). But to Python, a string is just a sequence of characters, so an index always gives you one character.
Trace 2#
1word = "seashells"
2print(word[3:6])
A)
sheB)
shelC)
ashD)
ashe
Answer:
A) she
Let’s count: s(0) e(1) a(2) s(3) h(4) e(5) l(6) l(7) s(8). The slice [3:6] starts at index 3 and stops before index 6, so we get indices 3, 4, and 5: she. If you picked B, remember the stop is not included. If you picked C or D, you may have started counting from 1 instead of 0.
Trace 3#
1name = " Joel "
2print(len(name))
3print(name[0] == "J")
A)
4thenTrueB)
6thenFalseC)
6thenTrueD)
4thenFalse
Answer:
B) 6 then False
The spaces at the beginning and end are characters too! So " Joel " has 6 characters, and the character at index 0 is a space " " instead of "J". If you picked A, you’re seeing the string the way your human eye does. Python sees those spaces! This is exactly the kind of thing that will trip you up with real-world data.
Trace 4#
1name = "joel"
2name[0] = "J"
3print(name)
A)
JoelB)
joelC) Error
D)
J
Answer:
C) Error
You get a TypeError: 'str' object does not support item assignment. Strings are immutable: you can’t change a character in a string directly, even though you can do this with a list. If you picked A, you were thinking of how this works with lists.
To get "Joel", you have to make a new string and assign it: name = "J" + name[1:].
Trace 5#
1email = "joelchan@umd.edu"
2print("umd" in email)
3print("UMD" in email)
4print("chan@" in email)
A)
TruethenTruethenTrueB)
TruethenFalsethenTrueC)
TruethenFalsethenFalseD)
FalsethenFalsethenTrue
Answer:
B) True then False then True
in checks whether the substring on the left appears anywhere in the string on the right. "umd" is in there. "UMD" is not, because uppercase and lowercase letters are different characters to Python. "chan@" is in there too: a substring can be any sequence of characters in a row, even if it crosses what we’d think of as the “parts” of the email. If you picked C, you may be thinking that in only finds whole “words.”
Trace 6#
1word = "mississippi"
2count = 0
3for char in word:
4 if char == "s":
5 count += 1
6print(count)
A)
2B)
4C)
11D)
1
Answer:
B) 4
Looping over a string gives you one character at a time. We add 1 to count each time the character is "s", and there are four s’s in “mississippi”. If you picked A, you may be counting the "ss" pairs instead of the individual characters. If you picked C, you counted all the characters (that would be len(word)).
Trace 7#
1code = "INFM322"
2print(code[-3:])
3print(code[:-3])
A)
322thenINFMB)
322thenINFM3C)
22thenINFM3D)
INFthenM322
Answer:
A) 322 then INFM
Negative numbers work in slices too. [-3:] starts at the 3rd-to-last character and goes to the end: “the last 3 characters.” [:-3] starts at the beginning and stops before the 3rd-to-last character: “everything except the last 3 characters.” If you picked B or C, remember that the stop is not included, even when it’s negative. If you picked D, you’re reading the negative numbers as counting from the front.
Part 2: Writing code with strings#
Now let’s flip it around: instead of predicting what code does, WRITE the code that does what the English description says. For each problem, ask yourself:
Do I want ONE character (indexing), or SEVERAL characters in a row (slicing)?
Is it easier to count from the front (0, 1, 2, …) or from the back (-1, -2, …)?
Do I need to build a new string (e.g., with
+)? Remember that you can’t change a string directly!
Write your code in the cell, run it to check that it gives you what you expect, then compare with the answer.
Write 1: Initials#
1first = "Sravya"
2last = "Rao"
3# print the initials, like "SR"
Answer:
1initials = first[0] + last[0]
2print(initials)
Index 0 gets the first character of each name, and + joins them together into a new string.
Write 2: Splitting a course code into its parts#
1code = "INST126"
2# print the department (the first four characters)
3
4# print the course number (everything after the department)
Answer:
1print(code[:4])
2print(code[4:])
Notice how the two slices fit together: [:4] stops before index 4, and [4:] starts at index 4. So they split the string at the same place, with nothing missing and nothing repeated. code[-3:] also works for the course number here, but only if all the course numbers are exactly 3 characters long. [4:] works as long as all the departments are 4 letters.
Write 3: Card ending in…#
1card_number = "4111222233334444"
2# print a message like "Card ending in 4444" (using the last 4 digits of the card number)
Answer:
1print("Card ending in " + card_number[-4:])
[-4:] gets the last 4 characters, no matter how long the card number is. A common mistake is card_number[-4:-1], which leaves out the last digit (the stop is not included!).
Write 4: Does the message mention a keyword?#
1message = "hi, I'd like a refund for my order please"
2keyword = "refund"
3# print True if the keyword is anywhere in the message, and False if it isn't
Answer:
1print(keyword in message)
in is a Boolean expression, so it evaluates to True or False. That means you could also use it directly as the condition in an if statement (e.g., if keyword in message:).
Write 5: Filtering by part of a string#
1# dates are always written as YYYY-MM-DD
2dates = ["2026-09-28", "2026-10-02", "2026-10-15", "2026-11-01", "2026-10-30"]
3october_dates = []
4# put only the dates that are in October (month "10") into october_dates, then print it
Answer:
1for date in dates:
2 if date[5:7] == "10":
3 october_dates.append(date)
4print(october_dates)
This prints ['2026-10-02', '2026-10-15', '2026-10-30']. Because the dates always follow the same pattern, the month is always at indices 5 and 6, so [5:7] grabs it. Counting it out is worth doing: 2(0) 0(1) 2(2) 6(3) -(4) 1(5) 0(6). This is our filtering pattern from Iteration, where the Boolean expression checks part of each string.
Watch out: "10" in date would not work here! It would also match "2026-11-10" (the 10th of November).
Write 6: Building an acronym#
1words = ["Portable", "Network", "Graphics"]
2acronym = ""
3# build up the acronym (the first letter of each word, like "PNG") in a loop, then print it
Answer:
1for word in words:
2 acronym = acronym + word[0]
3print(acronym)
This is the same accumulator pattern we used for adding up numbers, but with strings! We start with an empty string "" (instead of 0), and each time through the loop we make a new, longer string with + and reassign it to acronym. You can also write it as acronym += word[0].
Write 7: “Changing” a string#
1name = "joel"
2# change name so it starts with a capital J (without using any string methods), then print it
Answer:
1name = "J" + name[1:]
2print(name)
We can’t do name[0] = "J", because strings are immutable (see Trace 4). Instead, we build a new string: the new first letter, plus everything from index 1 onward. Then we assign that new string back to name. String methods (like .capitalize(), which we’ll get to soon) make this easier, but they follow the same rule: they give you back a new string, and you have to assign it if you want to keep it.
Working with strings: advanced#
Similar to lists, there is a collection of in-built string methods: functions in Python that operate on strings: https://docs.python.org/3/library/stdtypes.html#string-methods
I’m not going to show you all of them, but I will talk through them and discuss some fairly common ones
No need to memorize them – just know:
There are many methods that allow you to do things with strings – if you want to do something, first search for that method! It’s often way more efficient/bug-free than what you’ll write (even after you get good)
Where to find the exact code for it, how to figure out how they work
More importantly, I want you to practice reading documentation, get a sense of how to use functions (code that other people have written that you can reuse): what are the parameters? return values? what can you learn from examples? how do you learn how to use it appropriately in your own code?
1message = "Hello, my name is Inigo Montoya"
2# let's check if the message mentions my name!
3print("inigo" in message.lower())
True
Checking a string#
Common methods include:
.isnumeric()- is it all numeric?.isalnum()- is it all letters and numbers?.isalpha()- is it all letters?.startswith()- does it start with some substring?.endswith()- does it end with some substring?
Example: .isnumeric() checks if the string is entirely composed of numeric characters.
1a = " 123"
2a.isnumeric() # False! The leading space is not a numeric character
False
1# we want to do math
2a = "x123"
3b = "567"
4# but first we want to make sure the strings are all numbers before we convert them
5if a.isnumeric() and b.isnumeric():
6 a = int(a)
7 b = int(b)
8 print(a*b)
9else:
10 print("One of the input strings contains non-digits!")
One of the input strings contains non-digits!
Example application: cleaning a sales record!
1# need to turn into a number so I can do math with it
2sales_record = "$1,000,000"
3
4# with iteration
5cleaned = "" # initialize clean string as a blank/empty string
6# for each character in the sales record string
7for char in sales_record:
8 if char.isnumeric(): # if the character is numeric
9 cleaned += char # grab it (notice the use of concatenation here)
10print(cleaned)
1000000
Another example: .startswith() and .endswith() check whether the beginning/end of a string matches a substring (single character or sequence of characters).
1l = ["INST201", "INST126", "INFM322", "CMSC126", "joelchan@umd.edu", "joelchan", ".edu", "sarah@umd.edu"]
2# get all the strings that start with INST
3for item in l:
4 if item.startswith("INST"):
5 print(item)
INST201
INST126
PRACTICE: Use .startswith() to only grab the classes from CMSC
1course_codes = ["INST201", "INST126", "INFM322", "CMSC126"]
2target_courses = []
3# your code
Answer:
1for code in course_codes:
2 if code.startswith("CMSC"):
3 target_courses.append(code)
4target_courses # ['CMSC126']
Compare this with the in version from earlier: .startswith() only matches "CMSC" at the beginning of the string, which is what we really mean by “a CMSC class.”
PRACTICE: Use .endswith() to only grab the emails that are from .edu domain
1emails = ["oasislab@gmail.com", "joelchan@terpmail.umd.edu", "rony@terpmail.com", "joelchan@umd.edu", "joelchan@gmail.com", "sarahp@umd.edu", "sarah@umd.org"]
2
3target_emails = []
4# your code
Answer:
1for email in emails:
2 if email.endswith(".edu"):
3 target_emails.append(email)
4target_emails # ['joelchan@terpmail.umd.edu', 'joelchan@umd.edu', 'sarahp@umd.edu']
Same result as the in version for these emails, but .endswith() only matches ".edu" at the very end. So unlike in, it would correctly skip something like "joe.education@gmail.com".
PRACTICE: Write code that counts how many items in data are valid positive integers (contain only digits).
1data = ["42", "-7", "100", "3.5", "abc", "0", "99"]
2count = 0
3# your code here
Answer:
1data = ["42", "-7", "100", "3.5", "abc", "0", "99"]
2count = 0
3for item in data:
4 if item.isnumeric():
5 count += 1
6count # 4: "42", "100", "0", "99"
PRACTICE: Write code that grabs only the filenames that end with .csv from the list.
1files = ["data.csv", "notes.txt", "report.csv", "image.png", "grades.csv", "readme.md"]
2csv_files = []
3# your code here
Answer:
1files = ["data.csv", "notes.txt", "report.csv", "image.png", "grades.csv", "readme.md"]
2csv_files = []
3for f in files:
4 if f.endswith(".csv"):
5 csv_files.append(f)
6csv_files # ['data.csv', 'report.csv', 'grades.csv']
PRACTICE: Write code that checks each username and prints only the ones that are alphanumeric (letters and digits only, no special characters).
1usernames = ["joel86", "sarah!", "john_doe", "kacie2024", "mr.smith", "rony99"]
2valid = []
3# your code here
Answer:
1usernames = ["joel86", "sarah!", "john_doe", "kacie2024", "mr.smith", "rony99"]
2valid = []
3for u in usernames:
4 if u.isalnum():
5 valid.append(u)
6valid # ['joel86', 'kacie2024', 'rony99']
PRACTICE: Write code that separates the course codes into two lists: one for courses that start with "INST" and one for everything else.
1codes = ["INST126", "CMSC132", "INST201", "MATH140", "INST314", "PSYC100"]
2inst_courses = []
3other_courses = []
4# your code here
Answer:
1codes = ["INST126", "CMSC132", "INST201", "MATH140", "INST314", "PSYC100"]
2inst_courses = []
3other_courses = []
4for code in codes:
5 if code.startswith("INST"):
6 inst_courses.append(code)
7 else:
8 other_courses.append(code)
9inst_courses # ['INST126', 'INST201', 'INST314']
10other_courses # ['CMSC132', 'MATH140', 'PSYC100']
Practice: Code Tracing with Checking Methods#
Predict the output of each code snippet before running the cell!
Trace 1#
1print("2026".isnumeric())
2print("20.26".isnumeric())
A)
TruethenTrueB)
TruethenFalseC)
FalsethenFalseD)
2026then20.26
Answer:
B) True then False
.isnumeric() checks whether ALL the characters in the string are digits. "20.26" has a ., which is not a digit, so it’s False, even though it looks like a number to us. If you picked D, remember that checking methods give back a Boolean (True or False). They don’t give you back the string itself.
Trace 2#
1values = ["42", "-5", " 7", "3"]
2count = 0
3for v in values:
4 if v.isnumeric():
5 count += 1
6print(count)
A)
4B)
3C)
2D)
1
Answer:
C) 2
Only "42" and "3" are made up entirely of digits. "-5" has a -, and " 7" has a space at the start; neither of those is a digit. If you picked A, you’re thinking about whether each value means a number to you, rather than checking each character. If you picked B, look closely at " 7": that leading space counts!
Trace 3#
1course = "inst126"
2print(course.startswith("INST"))
A)
TrueB)
FalseC)
instD) Error
Answer:
B) False
"inst" and "INST" are different, because uppercase and lowercase letters are different characters. If you want a check that ignores case, normalize the string first, e.g., course.upper().startswith("INST") (more on this when we get to cleaning strings). If you picked C, remember that .startswith() gives back a Boolean. It doesn’t give you the beginning of the string.
Trace 4#
1filename = "report.CSV"
2print(filename.endswith(".csv"))
3print(filename.lower().endswith(".csv"))
4print(filename)
A)
FalsethenTruethenreport.csvB)
TruethenTruethenreport.CSVC)
FalsethenTruethenreport.CSVD)
FalsethenFalsethenreport.CSV
Answer:
C) False then True then report.CSV
The first check is False because ".CSV" and ".csv" are different. In the second line, filename.lower() makes a new lowercase string ("report.csv"), and that new string ends with ".csv", so it’s True. But we never assigned the lowercase version to anything, so filename is unchanged (strings are immutable!). If you picked A, that’s the immutability gotcha.
Trace 5#
1name = "Mary Jane"
2print(name.isalpha())
3print(name.replace(" ", "").isalpha())
A)
TruethenTrueB)
FalsethenTrueC)
FalsethenFalseD)
TruethenFalse
Answer:
B) False then True
.isalpha() checks that ALL the characters are letters, and a space is not a letter. So "Mary Jane" fails the check. Once we remove the space with .replace(" ", ""), we get "MaryJane", which is all letters. If you picked A, remember: spaces are characters too!
Trace 6#
1usernames = ["joel86", "sarah!", "kacie_2024", "rony99"]
2valid = []
3for u in usernames:
4 if u.isalnum():
5 valid.append(u)
6print(valid)
A)
['joel86', 'kacie_2024', 'rony99']B)
['joel86', 'rony99']C)
['sarah!', 'kacie_2024']D)
['joel86', 'sarah!', 'kacie_2024', 'rony99']
Answer:
B) ['joel86', 'rony99']
.isalnum() is True only if all the characters are letters or digits. "sarah!" has a !, and "kacie_2024" has an _, so neither passes. If you picked A, you may have assumed the underscore counts (it’s common in usernames, but it isn’t a letter or a digit). If you picked C, you flipped the filter: those are the usernames that fail the check.
“Cleaning” / normalizing a string#
Often we get data in string form, and we need to make sure it conforms to our expectations. Sometimes this means we modify it.
Common methods include:
.lower()or.upper()- convert the string to all lowercase or uppercase so we eliminate differences that have to do with case; remember thatAandaare different to Python!.replace()- replace parts of a string with something else - often we use this to strip out characters we don’t like (by replacing them with a blank string).strip()- remove hidden whitespace at the beginning and end of strings. super handy in data cleaning scenarios! closely related are.lstrip()and.rstrip()(can you guess what they do?)
Note: you can “chain” methods, and often want to do so! Often this is handy to “bundle together” cleaning/normalizing operations.
1# can use .replace() if you know in advance which characters you want to strip out
2def normalize_sales_record(sale):
3 return sale.replace("$","").replace(",","")
4
5sales_record = "$1,000,000"
6cleaned = normalize_sales_record(sales_record)
7print(cleaned)
1000000
Chaining works because a str.method() expression yields a string, which then is also able to do another .method(). We can do this as many times as we like, though be careful to make sure your code is still readable!
1def normalize_string(s):
2 return s.upper().strip() # convert the string to upper case and remove leading and trailing blank spaces
3
4# need to make sure it's normalized and we remove all weird stuff
5n = " Josh Lyman"
6m = "JOSH LYMAN"
7print(n)
8print(m)
9print(n == m)
10n_normal = normalize_string(n)
11m_normal = normalize_string(m)
12print(n_normal)
13print(m_normal)
14print(n_normal == m_normal)
Josh Lyman
JOSH LYMAN
False
JOSH LYMAN
JOSH LYMAN
True
PRACTICE: Given a list of names with messy whitespace, use .strip() to clean them and collect into a new list.
1raw_names = [" Alice", "Bob ", " Charlie ", "Diana"]
2cleaned_names = []
3# your code here
Answer:
1raw_names = [" Alice", "Bob ", " Charlie ", "Diana"]
2cleaned_names = []
3for name in raw_names:
4 cleaned_names.append(name.strip())
5cleaned_names # ['Alice', 'Bob', 'Charlie', 'Diana']
PRACTICE: Write code that checks if two strings are the “same” word regardless of case and whitespace. Print True or False.
1a = " Hello "
2b = "HELLO"
3# your code here
Answer:
1a = " Hello "
2b = "HELLO"
3print(a.strip().lower() == b.strip().lower()) # True
PRACTICE: Write code that takes a list of messy phone numbers and removes all dashes and spaces to produce clean digit-only strings.
1phones = ["301-555-1234", "240 555 5678", "301-555 9999", "2405554321"]
2cleaned_phones = []
3# your code here
Answer:
1phones = ["301-555-1234", "240 555 5678", "301-555 9999", "2405554321"]
2cleaned_phones = []
3for phone in phones:
4 cleaned_phones.append(phone.replace("-", "").replace(" ", ""))
5cleaned_phones # ['3015551234', '2405555678', '3015559999', '2405554321']
PRACTICE: Write code that normalizes a list of email addresses to lowercase, then counts how many are from umd.edu.
1emails = ["JoelChan@UMD.EDU", "sarah@gmail.com", "RONY@umd.edu", "pat@UMD.edu", "lee@yahoo.com"]
2count = 0
3# your code here
Answer:
1emails = ["JoelChan@UMD.EDU", "sarah@gmail.com", "RONY@umd.edu", "pat@UMD.edu", "lee@yahoo.com"]
2count = 0
3for email in emails:
4 if email.lower().endswith("umd.edu"):
5 count += 1
6count # 3
PRACTICE: Write code that takes a list of product names with inconsistent casing and extra whitespace, and produces a cleaned list where every name is title case (first letter capitalized) with no extra spaces.
1products = [" COFFEE mug", "water BOTTLE ", " LAPTOP stand ", "phone CASE"]
2cleaned = []
3# your code here
Answer:
1products = [" COFFEE mug", "water BOTTLE ", " LAPTOP stand ", "phone CASE"]
2cleaned = []
3for p in products:
4 cleaned.append(p.strip().lower().replace(" ", " ").title())
5cleaned # ['Coffee Mug', 'Water Bottle', 'Laptop Stand', 'Phone Case']
Note the chaining: .strip() → .lower() → .replace() → .title(). Each method returns a new string for the next method to work on.
PRACTICE: Write code that takes a messy list of hashtags and normalizes them: remove any leading/trailing spaces, convert to lowercase, and remove the # symbol. Collect the cleaned tags into a new list.
1tags = ["#Python ", " #DataScience", "#INST126 ", " #coding", "#Python"]
2cleaned_tags = []
3# your code here
Answer:
1tags = ["#Python ", " #DataScience", "#INST126 ", " #coding", "#Python"]
2cleaned_tags = []
3for tag in tags:
4 cleaned_tags.append(tag.strip().lower().replace("#", ""))
5cleaned_tags # ['python', 'datascience', 'inst126', 'coding', 'python']
Practice: Code Tracing with Cleaning/Normalizing#
Predict the output of each code snippet before running the cell!
Trace 1#
1s = " Hello World "
2result = s.strip()
3print(result)
4print(len(result))
A)
Hello Worldthen11B)
Hello Worldthen15C)
HelloWorldthen10D)
Hello Worldthen13
Answer:
A) Hello World then 11
.strip() removes leading and trailing whitespace only — it does not touch spaces inside the string. The original has 2 leading and 2 trailing spaces, so 15 - 4 = 11.
Trace 2#
1s = "Hello"
2s.lower()
3print(s)
A)
helloB)
HelloC)
HELLOD) Error
Answer:
B) Hello
Strings are immutable! .lower() returns a new string, but the result is never assigned to anything. s is unchanged.
Trace 3#
1s = "$1,200.50"
2s = s.replace("$", "").replace(",", "")
3print(s)
A)
$1,200.50B)
120050C)
1200.50D)
1,200.50
Answer:
C) 1200.50
The first .replace("$", "") removes the dollar sign → "1,200.50". The second .replace(",", "") removes the comma → "1200.50". The period is not removed because we didn’t replace it. And because we reassigned s = ..., the change is preserved.
Trace 4#
1a = " Python "
2b = "PYTHON"
3a = a.strip().upper()
4print(a == b)
5print(a)
A)
FalsethenPythonB)
TruethenPYTHONC)
FalsethenPYTHOND)
Truethenpython
Answer:
B) True then PYTHON
.strip() removes the spaces → "Python", then .upper() converts to "PYTHON". After reassignment, a is "PYTHON", which equals b.
Trace 5#
1msg = "aaa-bbb-ccc"
2msg = msg.replace("-", " ")
3msg = msg.upper()
4print(msg)
A)
AAA-BBB-CCCB)
aaa bbb cccC)
AAA BBB CCCD)
AAABBBCCC
Answer:
C) AAA BBB CCC
First .replace("-", " ") swaps dashes for spaces → "aaa bbb ccc". Then .upper() converts everything to uppercase → "AAA BBB CCC". Both results are reassigned to msg.
Trace 6#
1names = [" alice", "BOB ", " Charlie "]
2result = []
3for name in names:
4 result.append(name.strip().lower())
5print(result)
A)
['alice', 'bob', 'charlie']B)
[' alice', 'bob ', ' charlie ']C)
['Alice', 'Bob', 'Charlie']D)
['alice', 'BOB', 'Charlie']
Answer:
A) ['alice', 'bob', 'charlie']
Each iteration strips whitespace then lowercases: " alice" → "alice", "BOB " → "bob", " Charlie " → "charlie". The cleaned versions are appended to result.
“Parsing” a string (getting specific bits we want)#
You can do this if you know there is some separator that you can rely on to divide the string into the “bits” you want.
Examples:
Parse an email
Parse a URL
Parse a sentence into words!
Parse a time stamp
These all use the .split() method, which takes a separator parameter as input, and returns a list of strings that are separated around the separator.
Example: get elements of an email address.
1email = "joelchan@umd.edu"
2# we want to split the email into username and domain
3elements = email.split("@") # split on the `@` character
4print(elements)
5username = elements[0] # username is the 1st element in the split
6print(username)
['joelchan', 'umd.edu']
joelchan
1email = "joelchan@umd.edu"
2# if we only want the domain (.edu), we can do a multiple split
3split1 = email.split("@") # split the email by the @ separator
4domainserver = split1[1] # grab the second item
5split2 = domainserver.split(".") # split that second item by the . separator
6domain = split2[1] # get the second item from that one
7print(domain)
edu
Picture it: how .split() cuts up a string#
It helps to picture what .split() is doing under the hood. Python goes through the string looking for the separator. Each time it finds one, it makes a cut there. Then:
The separators themselves are THROWN AWAY.
Each piece is the slice of the string between the separators.
The pieces go into a new list, in order.
Let’s start with the simplest case: a string with one instance of a separator in it, which will get sliced into two pieces.
Notice how each piece is a slice you could have written yourself (the @ at index 8 isn’t in either slice!).
With more separators, we get more cuts, and so more pieces. A handy rule: N separators give you N + 1 pieces.
Now for the tricky one. What if two separators are right next to each other (like a double space)? Python still makes a cut at each separator, so there’s a piece between them. But there’s nothing in that piece, so it’s an empty string: s[8:8] starts and stops at the same place.
This is where the mysterious '' in your results comes from! (If you’re splitting words that might have extra spaces, .split() with no argument is smarter: it treats any run of whitespace as one separator, so you won’t get empty strings.)
Finally, what if the separator isn’t in the string at all? There’s nothing to cut, so you get the whole string back as the only piece. Notice that you still get a list back (with one item in it), instead of just the string.
This one is a common source of bugs: if you write "joelchan".split("@")[1] expecting the domain, you’ll get an IndexError, because the list only has an index 0. The key idea here is to make sure you understand what (and how many) separators are in your strings, to write appropriate .split() operations and avoid errors.
Syntax variations for .split()#
You’ll see (and can use) a few different ways to work with the result of .split(). They all do the same thing — pick whichever is clearest to you!
1. Store the list, then index into it (what we’ve been doing):
1email = "joelchan@umd.edu"
2parts = email.split("@")
3username = parts[0]
4print(username)
joelchan
2. Chain the index directly onto .split() — since .split() returns a list, you can index into it right away:
1email = "joelchan@umd.edu"
2username = email.split("@")[0]
3print(username)
joelchan
3. Unpacking — if you know exactly how many pieces .split() will produce, you can assign them to multiple variables at once:
1email = "joelchan@umd.edu"
2username, domain = email.split("@")
3print(username)
4print(domain)
joelchan
umd.edu
Unpacking is handy when you need all the pieces. But be careful: if the number of variables doesn’t match the number of pieces, you’ll get an error!
1# this will error — .split("@") gives 2 pieces but we have 3 variables
2a, b, c = "joelchan@umd.edu".split("@")
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[82], line 2
1 # this will error — .split("@") gives 2 pieces but we have 3 variables
----> 2 a, b, c = "joelchan@umd.edu".split("@")
ValueError: not enough values to unpack (expected 3, got 2)
Example: get elements of a url.
1url = "www.ischool.umd.edu"
2elements = url.split(".") # split on the `.` character
3elements[1]
'ischool'
PRACTICE: get elements of a timestamp (get the hour).
1# get hour
2timestamp = "13:30:31"
3# your code here
Answer:
1hour = timestamp.split(":")[0]
2print(hour) # '13'
The pieces are separated by :, and the hour is the first piece. Remember that .split() gives you back strings, so hour is the string "13" (and not the number 13). If you want to do math with it, convert it first: int(hour).
PRACTICE: get the words in a sentence.
1# get words
2message = "She sells seashells by the sea shore, with sea in the wind, and sea in my shoes"
3# your code here
Answer:
1words = message.split(" ")
2print(words)
Words are separated by spaces, so we split on " ". Look closely at the result, though: the punctuation stays attached to the words (e.g., 'shore,' and 'wind,'). If you wanted to count how many times "sea" shows up, you’d want to clean those off first (e.g., with .replace(",", "")).
A more complicated example: parse records string into a list of lists!
1records_string = "NAME\tSCORE\tGRADE\nJoel\t81\tB-\nRony\t98\tA+\nSravya\t99\tA+"
2
3records = []
4
5for row in records_string.split("\n"):
6 row_data = row.split("\t")
7 records.append(row_data)
8records
[['NAME', 'SCORE', 'GRADE'],
['Joel', '81', 'B-'],
['Rony', '98', 'A+'],
['Sravya', '99', 'A+']]
PRACTICE: A more complicated example: parse comma-separated records string into a list of lists!
1records_string = "NAME,SCORE,GRADE\nJoel,81,B-\nRony,98,A+\nSravya,99,A+"
2records = []
3# your code here
Answer:
1for row in records_string.split("\n"):
2 row_data = row.split(",")
3 records.append(row_data)
4records
5# [['NAME', 'SCORE', 'GRADE'], ['Joel', '81', 'B-'], ['Rony', '98', 'A+'], ['Sravya', '99', 'A+']]
This is the exact same code as the tab-separated example above. The only thing that changes is the separator for each row: "," instead of "\t".
PRACTICE: Given a list of full names, split each into first and last name, and collect just the last names into a list.
1full_names = ["Joel Chan", "Sarah Park", "John Smith", "Kacie Lee"]
2last_names = []
3# your code here
Answer:
1full_names = ["Joel Chan", "Sarah Park", "John Smith", "Kacie Lee"]
2last_names = []
3for name in full_names:
4 last = name.split(" ")[1]
5 last_names.append(last)
6last_names # ['Chan', 'Park', 'Smith', 'Lee']
You could also use unpacking: first, last = name.split(" ")
PRACTICE: Given a list of file paths, extract just the file extension (the part after the last .) for each one, and collect the unique extensions into a list.
1paths = ["data/report.csv", "images/photo.png", "docs/notes.txt", "data/grades.csv", "images/logo.png"]
2extensions = []
3# your code here
Answer:
1paths = ["data/report.csv", "images/photo.png", "docs/notes.txt", "data/grades.csv", "images/logo.png"]
2extensions = []
3for path in paths:
4 ext = path.split(".")[-1] # last piece after splitting on "."
5 if ext not in extensions:
6 extensions.append(ext)
7extensions # ['csv', 'png', 'txt']
PRACTICE: Given a log string where each entry is separated by | and has the format "LEVEL:message", extract only the messages (not the level) from entries where the level is "ERROR".
1log = "INFO:started|ERROR:disk full|INFO:retrying|ERROR:timeout|INFO:done"
2errors = []
3# your code here
Answer:
1log = "INFO:started|ERROR:disk full|INFO:retrying|ERROR:timeout|INFO:done"
2errors = []
3for entry in log.split("|"):
4 level, message = entry.split(":")
5 if level == "ERROR":
6 errors.append(message)
7errors # ['disk full', 'timeout']
Practice: Code Tracing with Parsing#
Predict the output of each code snippet before running the cell!
Trace 1#
1s = "a-b-c-d"
2parts = s.split("-")
3print(parts)
4print(len(parts))
A)
['a-b-c-d']then1B)
['a', 'b', 'c', 'd']then4C)
['a', '-', 'b', '-', 'c', '-', 'd']then7D)
'abcd'then4
Answer:
B) ['a', 'b', 'c', 'd'] then 4
.split("-") splits on every - character and removes the separators. The result is a list of the pieces between the dashes.
Trace 2#
1email = "joel@umd.edu"
2domain = email.split("@")[1]
3tld = domain.split(".")[1]
4print(tld)
A)
umdB)
eduC)
joelD)
umd.edu
Answer:
B) edu
First split: "joel@umd.edu".split("@") → ['joel', 'umd.edu'], index [1] → "umd.edu". Second split: "umd.edu".split(".") → ['umd', 'edu'], index [1] → "edu".
Trace 3#
1data = "10,20,30"
2nums = data.split(",")
3print(nums[0] + nums[1])
A)
30B)
1020C) Error
D)
10,20
Answer:
B) 1020
.split(",") returns ['10', '20', '30'] — a list of strings, not numbers! So nums[0] + nums[1] is string concatenation: "10" + "20" → "1020". To get 30, you’d need int(nums[0]) + int(nums[1]).
Trace 4#
1line = "Joel,81,B-"
2name, score, grade = line.split(",")
3print(name)
4print(type(score))
A)
Joelthen<class 'int'>B)
Joelthen<class 'str'>C)
Jthen<class 'str'>D) Error
Answer:
B) Joel then <class 'str'>
Unpacking assigns each piece of the split to a variable. .split() always returns a list of strings, even if the content looks numeric. So score is "81" (a string), not 81 (an integer).
Trace 5#
1msg = "one two three"
2words = msg.split(" ")
3print(words)
4print(len(words))
A)
['one', 'two', 'three']then3B)
['one', 'two', '', 'three']then4C)
['one two three']then1D)
['one', 'two', 'three']then4
Answer:
B) ['one', 'two', '', 'three'] then 4
There are two spaces between "two" and "three". When you split on a single space " ", each space is a separator, so the double space produces an empty string "" between them. This is a common gotcha! If you want to avoid this, use .split() with no argument, which splits on any whitespace and ignores extra spaces.
Trace 6#
1path = "home/user/docs/file.txt"
2parts = path.split("/")
3print(parts[-1])
4filename = parts[-1].split(".")
5print(filename[0])
A)
file.txtthenfileB)
docsthendocsC)
file.txtthenfile.txtD)
filethenfile
Answer:
A) file.txt then file
First split: path.split("/") → ['home', 'user', 'docs', 'file.txt']. Index [-1] → "file.txt". Second split: "file.txt".split(".") → ['file', 'txt']. Index [0] → "file".
REMEMBER: STRINGS ARE IMMUTABLE#
Remember! Unlike lists, string methods return a new object (and do not modify the original string), since strings are immutable.
This means if you don’t assign the return value of the string method to a new variable, the change will be lost. Remember this!
1a = "Hello"
2b = "WORLD"
3# these look like they should change a and b...
4a.lower()
5b.lower()
6# ...but they DON'T! a and b are unchanged:
7print(a, b) # still "Hello WORLD"
Hello WORLD
To actually preserve the change, you must reassign:
1a = "Hello"
2b = "WORLD"
3a = a.lower() # reassign the result back to a
4b = b.lower() # reassign the result back to b
5print(a, b) # now "hello world"
6print(a == b) # still False (different words), but both are lowercase now
hello world
False
1message = "Hello, my name is Inigo Montoya"
2print(message)
3# let's check if the message mentions my name!
4message = message.lower() # change to lower case
5message = message.replace("inigo", "MYSTERY")
6print(message)
Hello, my name is Inigo Montoya
hello, my name is MYSTERY montoya
String formatting#
So far we’ve taken strings as given, and we often specify a string directly. But frequently it is useful to compose a string programmatically, from variables.
Often this is done for debugging (to read the state of your program at various steps), but often this is used as outputs of your program, intermediate or final.
Here’s an example
1msg = "hello"
2friend = "rony"
3name = "anna"
4output = f"{msg} {friend}, my name is {name}!"
5print(output)
hello rony, my name is anna!
1weight_kgs = 120
2print(f"{weight_kgs} is {weight_kgs*2.2} lbs")
120 is 264.0 lbs
Example application: a guessing game!
1# game parameters
2name = "sarah"
3attempts = 5
4target = 138
5
6# initial guess
7guess = input("Guess the number (or type q to quit): ")
8
9# as long as there are attempts remaining
10# and the user hasn't said quit
11while attempts > 0 and guess != "q":
12 # change to number
13 guess_num = int(guess)
14
15 # if the guess is correct
16 if guess_num == target:
17 # congratulate the user
18 msg = f"congrats, {name}! {guess} is indeed the number!"
19 print(msg)
20 # and break out of the loop (no need to keep guessing!)
21 break
22 # otherwise
23 else:
24 # subtract 1 from the number of attempts
25 attempts -= 1
26 # tell the user how many attempts are left
27 msg = f"sorry that wasn't right, {name}, you have {attempts} remaining attempts"
28 print(msg)
29 # get another guess
30 guess = input("Take another guess (or type q to quit): ")
Note: this example uses input() and requires interactive input. Try running it in your own Python environment!
Example output:
Guess the number (or type q to quit): 3
sorry that wasn't right, sarah, you have 4 remaining attempts
Take another guess (or type q to quit): 5
sorry that wasn't right, sarah, you have 3 remaining attempts
Take another guess (or type q to quit): 138
congrats, sarah! 138 is indeed the number!
Here’s another example of f-strings used for debugging/tracing:
1sales = ["$100", "$250", "$500"]
2
3for i in range(len(sales)):
4 sale = sales[i]
5 print(f"Processing the item at index {i}: {sale}")
6 print(sale)
Processing the item at index 0: $100
$100
Processing the item at index 1: $250
$250
Processing the item at index 2: $500
$500
The basics#
Let’s look in more detail. The intuition here is that you’re defining a series of “slots” for variables. Each slot is indicated with the {} curly braces. And you put data / variables in them (which can include expressions that yield data!).
You also indicate that you’re doing this slot thing by prefixing the string with the letter f
Here’s how it looks:
1names = ["Joel", "Sarah", "Michael", "Kacie"]
2for name in names:
3 message = f"Welcome, {name}!"
4 print(message)
Welcome, Joel!
Welcome, Sarah!
Welcome, Michael!
Welcome, Kacie!
1birth_year = 1956
2this_year = 2023
3name = "Joel"
4message = f"Happy birthday, {name}! You are {this_year - birth_year} this year!"
5print(message)
Happy birthday, Joel! You are 67 this year!
PRACTICE: print out the following message for each row: “{name} got a {grade}”!
1records_string = "NAME,SCORE,GRADE\nJoel,81,B-\nRony,98,A+\nSravya,99,A+"
2for row in records_string.split("\n")[1:]:
3 name, score, grade = row.split(",")
4 # add your msg here!
Answer:
1records_string = "NAME,SCORE,GRADE\nJoel,81,B-\nRony,98,A+\nSravya,99,A+"
2for row in records_string.split("\n")[1:]:
3 name, score, grade = row.split(",")
4 msg = f"{name} got a {grade}"
5 print(msg)
Output:
Joel got a B-
Rony got a A+
Sravya got a A+
The [1:] skips the header row ("NAME,SCORE,GRADE"), so we don’t print "NAME got a GRADE".
Controlling the way it looks#
You can also control how the string looks! Various things like controlling how many decimal places are printed out (very useful when doing math), or how wide or indented the string is.
1# most common
2x = 2
3y = 3
4message = f"{x} divided by {y} is {x/y:.2f}" # only show two decimal places for the float value of result
5print(message)
2 divided by 3 is 0.67
The general design pattern here is to put a colon after and then specify some kind of formatting option. More details here: http://zetcode.com/python/fstring/
PRACTICE: complete the output message so it prints out something like this: “Please charge my card for $5.23” (if the total value is 5.23)
1tip = 0.18
2check = 25.00
3total_value = check + check*tip
4# complete the output msg
5# msg = f"..."
6# print(msg)
Answer:
1msg = f"Please charge my card for ${total_value:.2f}"
2print(msg) # Please charge my card for $29.50
The $ is outside the {}, so it’s just a regular character in the string. Inside the {}, :.2f shows exactly two decimal places, so we get 29.50 instead of 29.5.
PRACTICE: Given a list of items and prices, print a receipt where each line says "{item}: ${price:.2f}" and the last line says "Total: ${total:.2f}".
1items = ["Coffee", "Bagel", "Juice"]
2prices = [4.5, 3.75, 5.0]
3# your code here
Answer:
1items = ["Coffee", "Bagel", "Juice"]
2prices = [4.5, 3.75, 5.0]
3total = 0
4for i in range(len(items)):
5 print(f"{items[i]}: ${prices[i]:.2f}")
6 total += prices[i]
7print(f"Total: ${total:.2f}")
Output:
Coffee: $4.50
Bagel: $3.75
Juice: $5.00
Total: $13.25
PRACTICE: Given a CSV-style string of student records, parse it and print a report line for each student: "{name} scored {score}/100 ({percentage:.1f}%)" where percentage is the score out of 100.
1records_string = "Joel,81\nRony,98\nSravya,74\nKacie,92"
2# your code here
Answer:
1records_string = "Joel,81\nRony,98\nSravya,74\nKacie,92"
2for row in records_string.split("\n"):
3 name, score_str = row.split(",")
4 score = int(score_str)
5 percentage = score / 100 * 100
6 print(f"{name} scored {score}/100 ({percentage:.1f}%)")
Output:
Joel scored 81/100 (81.0%)
Rony scored 98/100 (98.0%)
Sravya scored 74/100 (74.0%)
Kacie scored 92/100 (92.0%)
PRACTICE: Given a list of distances in kilometers, print each one converted to miles using the format: "{km} km = {miles:.1f} miles" (1 km = 0.621371 miles).
1distances_km = [5, 10, 21.1, 42.2]
2# your code here
Answer:
1distances_km = [5, 10, 21.1, 42.2]
2for km in distances_km:
3 miles = km * 0.621371
4 print(f"{km} km = {miles:.1f} miles")
Output:
5 km = 3.1 miles
10 km = 6.2 miles
21.1 km = 13.1 miles
42.2 km = 26.2 miles
PRACTICE: Given a list of student names and a list of scores, print a numbered roster where each line is: "{rank}. {name} - {score}/100" where rank starts at 1.
1names = ["Sravya", "Rony", "Joel", "Kacie"]
2scores = [99, 98, 81, 92]
3# your code here
Answer:
1names = ["Sravya", "Rony", "Joel", "Kacie"]
2scores = [99, 98, 81, 92]
3for i in range(len(names)):
4 print(f"{i + 1}. {names[i]} - {scores[i]}/100")
Output:
1. Sravya - 99/100
2. Rony - 98/100
3. Joel - 81/100
4. Kacie - 92/100
Practice: Code Tracing with f-strings#
Predict the output of each code snippet before running the cell!
Trace 1#
1x = 5
2y = 3
3print(f"{x} + {y} = {x + y}")
A)
x + y = x + yB)
5 + 3 = 8C)
{5} + {3} = {8}D)
5 + 3 = 53
Answer:
B) 5 + 3 = 8
Inside {}, Python evaluates the expression. x is 5, y is 3, and x + y is 8 (integer addition, not string concatenation, because these are numbers). Text outside {} is literal.
Trace 2#
1name = "Joel"
2score = 85
3msg = f"{name} got {score}%"
4score = 90
5print(msg)
A)
Joel got 90%B)
Joel got 85%C)
Joel got score%D)
name got 85%
Answer:
B) Joel got 85%
The f-string is evaluated when it’s created (line 3), not when it’s printed (line 5). At creation time, score is 85. Changing score to 90 afterward doesn’t affect the already-created string.
Trace 3#
1val = 1/3
2print(f"{val}")
3print(f"{val:.2f}")
A)
0.3333333333333333then0.33B)
0.33then0.33C)
1/3then0.33D)
0.3333333333333333then0.3333333333333333
Answer:
A) 0.3333333333333333 then 0.33
Without formatting, the full float is printed. :.2f means “format as a float with 2 decimal places”, so it rounds to 0.33.
Trace 4#
1items = ["apple", "banana", "cherry"]
2for i in range(len(items)):
3 print(f"{i}: {items[i]}")
A)
0: apple1: banana2: cherryB)
1: apple2: banana3: cherryC)
apple: 0banana: 1cherry: 2D)
i: items[i](three times)
Answer:
A) 0: apple 1: banana 2: cherry
range(len(items)) gives 0, 1, 2. Each iteration, i is the index and items[i] is the value at that index. The f-string evaluates both expressions.
Trace 5#
1word = "hello"
2print(f"{word.upper()} has {len(word)} letters")
3print(word)
A)
HELLO has 5 lettersthenHELLOB)
HELLO has 5 lettersthenhelloC)
hello has 5 lettersthenhelloD)
HELLO has 5 lettersthen Error
Answer:
B) HELLO has 5 letters then hello
You can call methods and functions inside {}. word.upper() evaluates to "HELLO" and len(word) evaluates to 5. But remember: word.upper() returns a new string — it doesn’t change word. So word is still "hello" on the last line.
Trace 6#
1price = 49.99
2qty = 3
3total = price * qty
4print(f"Total: ${total:.2f}")
5print(f"Per item: ${total/qty:.2f}")
A)
Total: $149.97thenPer item: $49.99B)
Total: $149.97thenPer item: $50.00C)
Total: $150.0thenPer item: $49.99D)
Total: $149.970000thenPer item: $49.990000
Answer:
A) Total: $149.97 then Per item: $49.99
49.99 * 3 = 149.97. :.2f formats it to 2 decimal places → $149.97. total/qty = 149.97/3 = 49.99. The $ outside the {} is literal text, not special.
For the curious: there was a time when string formatting was done differently (but Python’s creators basically tell everyone not to use it anymore): just pointing it out as a historical novelty in case you see it in the wild in other people’s code (cough Joel’s code cough).
https://realpython.com/python-string-formatting/#1-old-style-string-formatting-operator