How to Format Strings and Insert Variables in Python
Formatting strings and inserting variables is an everyday need in Python, from building messages to creating reports and logs. Python gives you several ways to combine variables and text, each with its strengths. Below are the most common and recommended methods—with code examples and explanations.
Table of Content
Why Format Strings?
- Dynamic messages: Display user names, amounts, or results in output.
- Readable code: Keep string construction clean and maintainable.
- Complex formatting: Control number of decimals, alignment, and more.
01. Using f-Strings (Recommended, Python 3.6+)
F-strings provide an easy, modern way to embed variables directly in your string, using curly braces {}
:
name = "Alice"
score = 92
result = f"Hello, {name}! Your score is {score}."
print(result)
Output:
Hello, Alice! Your score is 92.
- Prefix your string with
f
and use variables or even expressions directly inside{}
. - Supports formatting, math, and function calls in-place (e.g.
{score/100:.2%}
for percent).
02. Using the format()
Method
str.format()
replaces {}
placeholders with values passed as arguments.
product = "notebook"
price = 15.99
msg = "The {} costs ${:.2f}".format(product, price)
print(msg)
Output:
The notebook costs $15.99
- Insert variables in order, or use names:
"{p} is ${v}".format(p=product, v=price)
. - You can use formatting codes for numbers, alignment, etc.
03. Using %
Formatting (Old Style)
The original Python method, still seen in older code but less preferred today:
user = "Bob"
items = 3
output = "User: %s has %d items" % (user, items)
print(output)
Output:
User: Bob has 3 items
%s
is for string,%d
for integer,%f
for float, etc.- Fewer formatting features and clarity, but still works for basics.
04. Using Concatenation with +
You can join strings and variables (converted to str
) with +
:
language = "Python"
version = 3
msg = "Learning " + language + " version " + str(version)
print(msg)
Output:
Learning Python version 3
- Every variable must be a string (use
str()
as needed). - Less flexible for complex or multi-type output, but works for quick joining.
05. Comparison Table: String Formatting Methods
Method | Readable | Type Safe | Complex Formatting | Best For |
---|---|---|---|---|
f-strings |
Yes | Yes | Yes | Modern Python, all uses |
format() |
Yes | Yes | Yes | Compatibility, named args |
% formatting |
Medium | No | Basic | Old code, quick cases |
Concatenation (+) |
Low | No | No | Very basic joins |
Conclusion
To format strings and insert variables in Python, prefer f-strings
for simplicity and power (Python 3.6+), or str.format()
for full compatibility and complex layouts. Use %
formatting or concatenation only in rare cases. Mastering these methods helps you write clean, clear, and professional Python output for any application.
Comments
Post a Comment