f-strings
Put variables inside text the easy way
You will build a lot of text in AI programs: prompts, messages, and answers. f-strings are the cleanest way to mix your variables into that text.
What is an f-string?
An f-string is a normal string with the letter f in front of the opening quote. Inside it, anything you put between curly braces { } is replaced by its value.
name = "Priya"
age = 28
message = f"My name is {name} and I am {age} years old."
print(message)
# My name is Priya and I am 28 years old.f stands for "formatted". Forgetting it is the most common mistake: without it, Python prints the braces literally.Why not just use +?
You can join strings with +, but you have to convert numbers with str() and keep track of every space. f-strings do the conversion for you.
| Feature | Using + | Using f-string |
|---|---|---|
| Code | "Age: " + str(age) | f"Age: {age}" |
| Needs str() for numbers | Yes | No |
| Easy to read | No | Yes |
Expressions inside braces
You are not limited to variable names. Any Python expression works inside the braces.
price = 20
quantity = 3
print(f"Total: {price * quantity}")
print(f"Shouting: {'hello'.upper()}")Formatting numbers
Add a colon after the value to control how it is shown. This is handy for prices, scores, and percentages.
score = 0.87654
cost = 1234.5
print(f"Score: {score:.2f}") # 2 decimal places -> 0.88
print(f"Accuracy: {score:.1%}") # as a percent -> 87.7%
print(f"Cost: {cost:,.2f}") # thousands separator -> 1,234.50f-strings in AI programs
This is where f-strings really shine. When you talk to a language model, you usually build the prompt from pieces of data.
topic = "black holes"
level = "a 10-year-old"
prompt = f"Explain {topic} to {level} in three short sentences."
print(prompt)For long prompts, use triple quotes. f-strings work there too.
user_name = "Sam"
question = "What is a list?"
prompt = f"""You are a friendly Python tutor.
The student's name is {user_name}.
Answer this question: {question}"""
print(prompt)Common mistakes
- Forgetting the
f:"Hi {name}"prints the braces as text. - Using the same quote type inside the braces as outside. Use
'inside if the f-string uses". - Writing a literal brace: use double braces
{{ }}if you want a real{in the output.
What's next?
Next you'll learn how to grab individual characters and pieces of a string with indexing and slicing.