To print a variable in Python, pass it to print(). To print it with text, use an f-string: print(f"Total: {total}"). A comma works too, but it adds a space between items:
total = 59.97
print(total)
print(f"Total: ${total}")
print("Total:", total)
The rest of this guide covers numbers, dollars, several variables at once, a variable’s name and value, and capturing output. Every example ran on Python 3.14.7, and the outputs are real.
Print a variable in Python with print()
print() takes any value and writes its text form to the screen. Here it is with the common types:
city = "Denver"
price = 19.99
qty = 3
in_stock = True
tags = ["sale", "new"]
item = {"sku": "A-102", "price": 19.99}
print(city)
print(price)
print(qty)
print(in_stock)
print(tags)
print(item)
print(repr(city))
Output:
Denver
19.99
3
True
['sale', 'new']
{'sku': 'A-102', 'price': 19.99}
'Denver'
Strings print without quotes, and lists and dictionaries print the way you’d type them. True prints as a word, and numbers print as they are.
repr(city) added the quotes back. That’s also what you see when you type a variable’s name alone in the interactive shell, which is why the shell shows 'Denver' while print() shows Denver.
New to variables themselves? Python variables explained covers naming and types before you print them.
Print a string and variable together
This is the question most people are really asking. There are three everyday ways, and they don’t behave the same:
item = "coffee"
price = 19.99
qty = 3
print("Item:", item, "Qty:", qty)
print("Price: $", price)
print("Price: $", price, sep="")
print(f"Price: ${price}")
print("Qty: " + str(qty))
try:
print("Qty: " + qty)
except TypeError as err:
print("TypeError:", err)
Output:
Item: coffee Qty: 3
Price: $ 19.99
Price: $19.99
Price: $19.99
Qty: 3
TypeError: can only concatenate str (not "int") to str
A comma prints each item with a space between them. That’s fine for Item: coffee, but it put a gap after the dollar sign in Price: $ 19.99.
sep="" removes those spaces, and the f-string version needs no fix at all. I reach for an f-string whenever the spacing matters.
The + operator only joins a string to a string. "Qty: " + qty raised TypeError because qty is an integer, so wrap it in str() or use an f-string.
Printing strings and integers together goes deeper into that error. To build a string for later instead of printing it, see inserting a variable into a string.
Format variables inside an f-string
An f-string does more than drop a variable into text. A format spec after a colon controls decimals, commas, percentages and dates:
from datetime import date
price = 1234567.891
rate = 0.4567
qty = 3
shipped = date(2026, 9, 30)
print(f"Price: ${price:,.2f}")
print(f"Rounded: {price:.0f}")
print(f"Rate: {rate:.1%}")
print(f"Padded: {qty:03d}")
print(f"Shipped: {shipped:%B %d, %Y}")
print(f"Total: ${price * qty:,.2f}")
print(f"Braces: {{qty}} = {qty}")
Output:
Price: $1,234,567.89
Rounded: 1234568
Rate: 45.7%
Padded: 003
Shipped: September 30, 2026
Total: $3,703,703.67
Braces: {qty} = 3
:,.2f gives two decimals with thousands separators, which is what you want for US dollar amounts. :.1% multiplies by 100 and adds the percent sign.
Dates accept the same codes as strftime(), so :%B %d, %Y printed September 30, 2026. The expression price * qty ran inside the braces, and doubled braces printed literal ones.
For more on number formats, see printing 2 decimal places in Python and formatting numbers with commas.
Quotes inside an f-string
Printing a dictionary value inside an f-string means quotes inside quotes:
order = {"city": "Austin", "state": "TX"}
print(f"Ship to {order['city']}, {order['state']}")
print(f"Ship to {order["city"]}, {order["state"]}")
Output:
Ship to Austin, TX
Ship to Austin, TX
Both lines work on Python 3.12 and later. On 3.11 and older, reusing the outer double quotes inside the braces is a SyntaxError, which I confirmed on Python 3.8. Single quotes inside work on every version.
Print multiple variables on one line
Pass several variables to one print() call, and control what goes between and after them with sep and end:
first, last, age = "Ava", "Johnson", 34
print(first, last, age)
print(first, last, age, sep=", ")
print(first, last, sep="_", end="!\n")
print("Loading", end="")
print("...", end=" ")
print("done")
states = ["TX", "CA", "NY"]
print(states)
print(*states)
print(*states, sep=" | ")
Output:
Ava Johnson 34
Ava, Johnson, 34
Ava_Johnson!
Loading... done
['TX', 'CA', 'NY']
TX CA NY
TX | CA | NY
sep replaces the space between items, and end replaces the newline at the end. With end="", the next print() continues on the same line, which is how the loading message came out on one line.
A list prints with brackets and quotes. The * in print(*states) unpacks it, so each item prints as a separate argument and sep applies to them.
There’s more on this in printing on the same line in Python and printing a new line after a variable.
Print a variable’s name and value
For debugging, Python 3.8 added a shortcut: put = after the variable in an f-string and it prints the name too.
price = 19.99
qty = 3
city = "Denver"
print(f"{price=}")
print(f"{price = }")
print(f"{price=:.1f}")
print(f"{city=}")
print(f"{city=!s}")
print(f"{price * qty=:.2f}")
Output:
price=19.99
price = 19.99
price=20.0
city='Denver'
city=Denver
price * qty=59.97
= in an f-string prints the expression, then its value.Spaces around the = are kept in the output, and a format spec still works after it. It also works on whole expressions, as price * qty shows.
Notice the quotes in city='Denver'. The = form uses repr() by default, and !s switches it back to the plain text you’d get from print(city).
Print the type of a variable
When a value doesn’t print the way you expect, check its type. type() gives the class, and .__name__ gives just the name:
values = [42, 19.99, "42", True, None, [1, 2]]
for v in values:
print(f"{v!r:<8} {str(type(v)):<18} {type(v).__name__}")
Output:
42 <class 'int'> int
19.99 <class 'float'> float
'42' <class 'str'> str
True <class 'bool'> bool
None <class 'NoneType'> NoneType
[1, 2] <class 'list'> list
42 and '42' look almost the same when printed, but one is an int and one is a str. That’s often the cause of a TypeError when you combine them.
type(v).__name__ drops the <class ...> wrapper. In an if statement, test with isinstance(v, int) instead of comparing types.
Print to a variable: capture print output
print() writes to the screen and returns None, so result = print(...) doesn’t save anything. To keep the text, capture it:
import io
from contextlib import redirect_stdout
result = print("Hello")
print("print() returned:", result)
buffer = io.StringIO()
with redirect_stdout(buffer):
print("Order", 1042, "shipped")
print("Total: $59.97")
captured = buffer.getvalue()
print("captured:", repr(captured))
log = io.StringIO()
print("Refund", 1043, file=log)
print("log:", repr(log.getvalue()))
Output:
Hello
print() returned: None
captured: 'Order 1042 shipped\nTotal: $59.97\n'
log: 'Refund 1043\n'
print() returns None; redirect_stdout and file= capture the text instead.redirect_stdout sends every print() inside the with block to a StringIO buffer, which is useful for testing code you can’t change. The file= argument does the same for a single call.
If you only need the text in a variable, skip print() and build an f-string directly. To write output to a file on disk, see writing a variable to a file.
What do %s, %d and %f mean in a Python print?
Older code, and many search results, use % formatting or str.format(). You’ll need to read both:
city, qty, price = "Denver", 3, 19.99
print("%s: %d items at $%.2f" % (city, qty, price))
print("{}: {} items at ${:.2f}".format(city, qty, price))
print("{0} has {1} items, and {0} ships today".format(city, qty))
Output:
Denver: 3 items at $19.99
Denver: 3 items at $19.99
Denver has 3 items, and Denver ships today
In % formatting, %s means a string, %d an integer and %.2f a float with two decimals. The values go in a tuple after the %.
format() uses braces instead, and numbered braces let you reuse a value. Both still work in Python 3.14, but f-strings are shorter and easier to read, so I use them for new code.
Common print variable errors and fixes
These are the errors I see most when printing variables. The first comes from Python 2 code:
total = 59.97
print "Total:", total
Output (error):
File "C:\pyguides\receipt_py2.py", line 2
print "Total:", total
^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?
In Python 3, print is a function and needs parentheses. The fix is print("Total:", total), and Python’s error message suggests it for you.
Three more, caught and printed so you can see the messages:
city = "Denver"
total = None
try:
print("Total: " + total)
except TypeError as err:
print("1.", err)
try:
print(f"{city:.2f}")
except ValueError as err:
print("2.", err)
name = "Ava"
greeting = t"Hi {name}"
print("3.", greeting)
print("4.", f"Hi {name}")
Output:
1. can only concatenate str (not "NoneType") to str
2. Unknown format code 'f' for object of type 'str'
3. Template(strings=('Hi ', ''), interpolations=(Interpolation('Ava', 'name', None, ''),))
4. Hi Ava
1. Adding None to a string fails just like an integer does. It usually means a function returned nothing, so check the value before printing it.
2. :.2f only works on numbers. The string "Denver" raised ValueError, which often means a number arrived as text from input() or a CSV file.
3. Python 3.14 added t-strings, which look like f-strings with a t. Printing one shows a Template object, not text, so use f when you just want to print.
Example: print a sales receipt with variables
Here’s everything together: f-strings, alignment and dollar formatting in a short receipt.
from datetime import date
store, city, state = "Lakeside Market", "Denver", "CO"
items = [("Coffee beans", 2, 14.99), ("Oat milk", 3, 4.49), ("Bagels", 1, 6.25)]
tax_rate = 0.0881
print(f"{store} - {city}, {state}")
print(f"{date(2026, 9, 30):%B %d, %Y}")
print("-" * 36)
print(f"{'Item':<16}{'Qty':>4}{'Amount':>16}")
subtotal = 0
for name, qty, price in items:
line = qty * price
subtotal += line
money = f"${line:,.2f}"
print(f"{name:<16}{qty:>4}{money:>16}")
tax = subtotal * tax_rate
print("-" * 36)
totals = [
("Subtotal", subtotal),
(f"Tax ({tax_rate:.2%})", tax),
("Total", subtotal + tax),
]
for label, amount in totals:
money = f"${amount:,.2f}"
print(f"{label:<20}{money:>16}")
Output:
Lakeside Market - Denver, CO
September 30, 2026
------------------------------------
Item Qty Amount
Coffee beans 2 $29.98
Oat milk 3 $13.47
Bagels 1 $6.25
------------------------------------
Subtotal $49.70
Tax (8.81%) $4.38
Total $54.08
:<16 and :>16 line up columns in plain text.:<16 left-aligns text in 16 characters and :>16 right-aligns it. Each amount is formatted as a dollar string first, then aligned, so the dollar sign stays next to the number.
The tax label is an f-string built inside the totals list, and :.2% turned 0.0881 into 8.81%. Change tax_rate for your state and the label follows.
For more on strings and output, these fit well next:
- Concatenate strings in Python
- Use a new line in Python strings
- Insert a variable into a string
- Print 2 decimal places in Python
Frequently asked questions
How do I print a variable in Python?
Pass it to print(): print(total). To print it with text, use an f-string like print(f"Total: {total}").
How do I print a string and a variable on the same line?
Use an f-string, print(f"Name: {name}"), or a comma, print("Name:", name). The comma adds a space between the items.
Why do I get can only concatenate str (not int) to str?
You used + to join text and a number. Wrap the number in str(), or use an f-string or a comma instead.
How do I print a variable’s name and value?
Add = inside an f-string: print(f"{price=}") prints price=19.99. It needs Python 3.8 or later.
How do I print a variable without a space?
Use an f-string, or pass sep="" to print() so the items aren’t separated by spaces.
How do I print a variable with two decimal places?
Use a format spec: print(f"{price:.2f}"). Add a comma, :,.2f, for thousands separators.
How do I save print output to a variable?
print() returns None. Build the text with an f-string instead, or capture output with contextlib.redirect_stdout. The Python print() documentation lists every argument.
Bijay Kumar is a 13-time Microsoft MVP with more than 18 years in software development, and the founder of Python Guides and TSinfo Technologies. He started out building .NET and SharePoint solutions at HP, TCS and KPIT before moving into Python, machine learning and AI, and he also builds web apps with TypeScript and React. He writes the tutorials here himself, and every example is run before publishing so you see the real output. More about Bijay · Microsoft MVP profile · LinkedIn