In Python, you can use {}
as placeholders for strings and use format()
to fill in the placeholder with string literals. For example:
print("You have {} apples.".format(5))
# this will print:
# You have 5 apples.
The format()
method lets you list out the strings you want to place in relation to the {}
as it appears. This means that you can have more than one {}
as placeholders.
Here is a Python example of multiple {}
used with format()
.
print("You have {} apple{}.".format(5, 's'))
# this will print:
# You have 5 apples.
You can also add variables to format()
in Python, in place of literals. Here is an example:
language = "Python"
print("I'm coding in {}").format(language)
# this will print:
# I'm coding in Python
What you passed in can also include conditional logic. For example:
apples = 5
plural = "s" if apples != 1 else ""
print("You have {} apple{}.".format(apples, plural))
# this will print:
# You have 5 apples.
It is good to note that you can use Python's format()
with any strings. For example:
speak = "You have {} apple{}.".format(5, 's')
print(speak)
# this will print:
# You have 5 apples.
Other notes on format() in Python
format()
will automatically interpret value by type. For example, a float
will be reduced to a single trailing zero.
x = "num = {}".format(1.00000000000)
print(x)
# this will print
# num = 1.0
x = "num = {}".format(1.000000000005)
print(x)
# this will print
# num = 1.000000000005
When it comes to format()
and float
, you can force a value to be interpreted as a float
by using {:f}
instead of your regular {}
. By default, a floating number will show 6 trailing zeros. Here is an example:
x = "num = {:f}".format(1)
print(x)
# this will print
# num = 1.000000
You can also specify the number of trailing digits after the decimal point by adding the number with a decimal point before f
. For example, to have 2 digits after the decimal point, you will write your {}
placeholder as {:.2f}
Here is an example of how to use it:
money = "you have ${:.2f} in your account".format(100)
print(money)
# this will print
# you have $100.00 in your account
Using % instead of {} as placeholders in Python
Oftentimes, we see %
used as placeholders in Python code. This can be used as a placeholder instead of {}
. Another %
is used as a separator, followed by the values to be placed in the placeholder.
The difference between using {}
and %
is that you can specify the type, enforcing a certain expectation that whatever gets placed in the string literal is either a number or a string. For example, the placeholder %i
expects an integer
, and %s
will expect a string literal.
Here is an example of using %
as placeholders in Python:
print("values: %i, strings: %s"%(2+2, "2+2"))
# this will print:
# values: 4, strings: 2+2
print("values: %i, strings: %i"%(2+2, "2+2"))
# this will print:
# TypeError: %i format: a number is required, not str