String interpolation
String interpolation allows you to mix simple Python expressions into strings.
food = 'pizza'
print(f'Hello, my favorite food is {food}.')
When using string interpolation, the string starts with the letter f
, outside
of the quotes. Inside the quotes, you can put Python expressions inside of curly
brackets.
In the example above, because the string starts with f
, Python sees the
variable food
inside the curly brackets, and it substitutes the value of
food
— pizza — for the variable. The result is:
Hello, my favorite food is pizza.
You can use as many expressions as you want:
def print_info(name, age, food):
print(f"{name} is {age} years old. \n{name}'s favorite food is {food}.")
print_info('Anna', 23, 'lasagna')
This will print:
Anna is 23 years old.
Anna's favorite food is lasagna.
Expressions
You can put expressions inside of the curly brackets. For example:
rating = 6
print(f'I give that movie a {rating} out of 10.')
print(f'Oh yeah? I liked it twice as much, so I gave it a {rating*2} out of 10.')
Notice how we can use an expression, rating*2
in the curly brackets. This
prints:
I give that movie a 6 out of 10.
Oh yeah? I liked it twice as much, so I gave it a 12 out of 10.
Here is another example:
def print_maximum(numbers):
print(f'The maximum value is: {max(numbers)}')
print_maximum([53, 210, 35])
This will print:
The maximum value is: 210
Example
Given a name, pronoun, major, and hometown, write a function that would write out the information in the following format:
Alice is from Beaverdam.
At BYU, she is majoring in Sociology.
Do you know anyone else from Beaverdam?
Here is a solution:
def print_info(name, pronoun, major, hometown):
print(f'{name} is from {hometown}.')
print(f'At BYU, {pronoun} is majoring in {major}.')
print(f'Do you know anyone else from {hometown}?')
print_info('Alice', 'she', 'Sociology', 'Beaverdam')
Now let’s do the same thing, but print the output to a file:
def print_info(file, name, pronoun, major, hometown):
file.write(f'{name} is from {hometown}.\n')
file.write(f'At BYU, {pronoun} is majoring in {major}.\n')
file.write(f'Do you know anyone else from {hometown}?\n')
with open('all_about_alice.txt', 'w') as file:
print_info(file, 'Alice', 'she', 'Sociology', 'Beaverdam')
Take a look at this code. The print_info()
function takes a file as its first
argument. We could have given this function a filename and had it open the file
before writing to it. Instead, we open the file outside of the function, and
pass the function an open file object. This lets the function focus on just one
job.
Organizing the code this way makes it easy for us to write multiple things to the same file. For example:
with open('information.txt', 'w') as outfile:
print_info(outfile, 'Jason', 'he', 'Computer Science', 'someplace in Alaska 🥶')
print_info(outfile, 'Isabella', 'she', 'Computer Science', 'Arizona 🥵')