How to Insert Values (String Interpolation) in Python String
The process of evaluating a string literal containing one or more placeholders is called String interpolation and it is a fundamental skill in Python. Whether you are generating dynamic SQL queries, constructing user messages, or formatting data for a CSV file, you need to insert variable values into strings efficiently.
This guide explores the four primary methods to insert values into Python strings, ranging from the modern "f-string" to legacy operators.
Method 1: f-Strings (Recommended)
Introduced in Python 3.6, Formatted String Literals (f-strings) are the most readable and efficient way to insert values. They are created by prefixing the string with f or F. You can embed Python expressions directly inside curly braces {}.
name = "Alice"
role = "Developer"
# ✅ Correct: Variables are evaluated directly inside the string
message = f"Hello, {name}. You are logged in as a {role}."
print(message)
# You can also evaluate expressions
calc = f"Five plus five is {5 + 5}."
print(calc)
Output:
Hello, Alice. You are logged in as a Developer.
Five plus five is 10.
Why use this? It handles type conversion automatically and is faster than other methods.
Method 2: The .format() Method
Before f-strings, the .format() method was the standard. It is still useful when the format string is supplied by a user (e.g., from a config file) rather than hardcoded in the script.
name = "Bob"
age = 30
# ✅ Positional arguments (Order matters)
text_pos = "Name: {}, Age: {}".format(name, age)
print(text_pos)
# ✅ Keyword arguments (Order doesn't matter)
text_key = "Name: {n}, Age: {a}".format(a=age, n=name)
print(text_key)
Output:
Name: Bob, Age: 30
Name: Bob, Age: 30
Method 3: The % Operator (Legacy)
This is the oldest method, similar to printf in C. While still supported, it is generally discouraged for complex strings due to readability issues.
name = "Charlie"
count = 5
# %s = string, %d = integer
# ⛔️ Legacy style (Less readable for many variables)
print("User %s has %d items." % (name, count))
Output:
User Charlie has 5 items.
Method 4: String Concatenation
Beginners often try to join strings using the + operator. While simple, this method requires manual type conversion and gets messy quickly.
name = "Dave"
score = 98
# ⛔️ Error: Cannot concatenate string and integer
try:
print("User " + name + " scored " + score)
except TypeError as e:
print(f"Error: {e}")
# ✅ Correct: Must manually cast integer to string
print("User " + name + " scored " + str(score))
Output:
Error: can only concatenate str (not "int") to str
User Dave scored 98
Advanced Formatting (Precision and Alignment)
Both f-strings and .format() support a mini-language for formatting numbers, such as controlling decimal places or padding text.
Decimal Precision
To display floating-point numbers with specific precision, use :.2f (for 2 decimal places).
price = 49.99123
# ✅ Round to 2 decimal places
print(f"Price: ${price:.2f}")
Output:
Price: $49.99
Alignment and Padding
You can align text using < (left), > (right), or ^ (center), followed by the width.
header = "Menu"
# ✅ Center align within 20 characters, padded with '*'
print(f"{header:*^20}")
# ✅ Right align numbers
value = 100
print(f"Value: {value:>10}")
Output:
********Menu********
Value: 100
Conclusion
To insert values into Python strings efficiently:
- Use f-strings (
f"{var}") for 99% of use cases. They are the fastest and most readable. - Use
.format()if you are working with legacy code or template strings stored in external files. - Avoid concatenation (
+) for combining text and numbers, as it requires manual casting.