Table of Contents
Why Combine Text and Variables?
Many programs need to display messages that include changing information: a user’s name, a score, a date, a calculated result, and so on. That information is usually stored in variables.
Combining fixed text (string literals) with values stored in variables is how you create clear, useful messages for users, logs, and reports.
In this chapter, you will see different ways to:
- Join text and variable values
- Avoid common errors when combining strings and other data types
- Format messages in readable and flexible ways
All of this builds on your knowledge of strings and basic operations.
Using `+` to Concatenate Strings
The simplest way to combine text and variables (that are already strings) is string concatenation with +.
first_name = "Ada"
last_name = "Lovelace"
full_name = first_name + " " + last_name
print("Hello, " + full_name + "!")Output:
Hello, Ada Lovelace!Key points:
+between strings joins them together.- You can include spaces as separate string pieces:
" ".
This works only when all parts are strings.
Converting Non-Strings with `str()`
If you try to concatenate a string with a number directly, Python will raise an error.
age = 30
# print("Your age is " + age) # This will cause an error
To fix this, convert the non-string value to a string using str():
age = 30
message = "Your age is " + str(age)
print(message)Output:
Your age is 30
You’ll often use str() with:
- Integers:
int - Floats:
float - Booleans:
bool
Examples:
score = 98
print("Score: " + str(score))
pi = 3.14159
print("Pi is approximately " + str(pi))
is_logged_in = True
print("Logged in: " + str(is_logged_in))Using Commas in `print()`
Another easy way to combine text and variables is to pass them as separate arguments to print(), separated by commas.
name = "Sam"
age = 25
print("Name:", name, "| Age:", age)Output:
Name: Sam | Age: 25What happens here:
print()automatically converts non-strings to strings.print()automatically adds a space between each argument.
So you don’t need to use str() or + when you do this.
Compare:
age = 25
# Using +
print("Age: " + str(age))
# Using commas
print("Age:", age)Both produce:
Age: 25
Age: 25Using commas is convenient for quick output, especially during testing or debugging.
Basic f-Strings (Formatted String Literals)
f-strings provide a powerful and readable way to combine text and variables. They work in Python 3.6+.
You write a string with a leading f and insert variables inside {}:
name = "Lina"
age = 21
message = f"Hello, {name}. You are {age} years old."
print(message)Output:
Hello, Lina. You are 21 years old.Advantages of f-strings:
- You don’t need
+orstr(). - You can see the structure of the message clearly.
- You can include expressions, not just simple variable names.
Example with an expression inside {}:
length = 5
width = 3
print(f"Area: {length * width}")Output:
Area: 15Controlling Number Formatting in f-Strings
f-strings can format numbers directly inside {} using a colon and a format specifier.
Limiting Decimal Places
pi = 3.14159265
print(f"Pi (2 decimals): {pi:.2f}")
print(f"Pi (4 decimals): {pi:.4f}")Output:
Pi (2 decimals): 3.14
Pi (4 decimals): 3.1416Explanation:
:.2fmeans: format as a floating-point number with 2 decimal places.:.4fmeans: 4 decimal places.
Padding Numbers (Basic)
You can pad integers with leading zeros:
order_number = 42
print(f"Order ID: {order_number:05d}")Output:
Order ID: 00042Here:
05dmeans: integer (d), width 5, pad with zeros on the left.
Building Messages Step by Step
Sometimes you’ll construct a message gradually by adding pieces.
name = "Alex"
score = 87
message = "Player: " + name
message = message + " | Score: " + str(score)
print(message)Or, using f-strings from the start:
name = "Alex"
score = 87
message = f"Player: {name}"
message += f" | Score: {score}"
print(message)Output in both cases:
Player: Alex | Score: 87Note:
message += ...is a shorthand formessage = message + ....
Newlines and Special Characters in Combined Text
You can include special characters like the newline \n inside your strings to format the output.
name = "Aisha"
score = 120
message = f"Player: {name}\nScore: {score}"
print(message)Output:
Player: Aisha
Score: 120You can combine this with any of the techniques above.
Choosing a Technique
Here’s a quick comparison:
+withstr()- Good for: simple, quick combinations when you know everything is a string (or you’re comfortable calling
str()). - Example:
"Total: " + str(total)- Commas in
print() - Good for: quick output while testing; you don’t care about exact spacing or format details.
- Example:
print("Total:", total)- f-strings
- Good for: most real programs; clear, readable, flexible formatting.
- Example:
print(f"Total: {total}")In practice, f-strings are often the most convenient and readable option.
Practice Examples
Try to write code for these tasks:
- Store your name and city in variables and print a message like:
Hello, Alice from London!using: +andstr()if needed- An f-string
- Ask the user for their name and age (you’ll formally learn input in a later chapter, but assume you have them in variables
nameandage), then create: message1 = "Name: " + name + ", Age: " + str(age)message2 = f"Name: {name}, Age: {age}"
Print both.- Given:
product = "Book"
price = 12.5Print:
Book costs 12.5Book costs 12.50(with exactly 2 decimal places)
using f-strings.