String formatting: Part 2
Contents
String formatting: Part 2#
Table of Contents
In part 1 we learned about formatting strings,
sometimes called the formatting spec (short for specification), which are used
to tell Python how a value should be displayed. And we learned how to use them
in the format()
function.
Today we are going to learn some of the other ways to use formatting strings.
The format()
function#
First lets do a quick review of the format()
function.
format(VALUE, SPEC)
|
the value to format |
|
the formatting specification |
In this example, the VALUE
is "Monday"
.
The SPEC
is ".3s"
which means:
a precision of
3
should be usedwith a
string
presentation
format("Monday", ".3s")
'Mon'
The str.format()
method#
The .format()
method on str
objects also uses formatting strings. Here is
how we would do the same thing with the .format()
method.
"{0:.3s}".format("Monday")
'Mon'
{POSITION:SPEC}.format(VALUE)
|
curly braces placeholders which indicate where the value should go |
|
argument position |
|
a colon is used to indicate that the |
|
the formatting specification |
|
the value to format |
You might be wondering where that 0
for POSITION
come from.
Well you see, one of the advantages to using .format()
is that you can pass
it multiple values. When you do that, each argument has its own position.
"{0:.3s} {1:.2f}".format("Monday", 5.2423)
'Mon 5.24'
If you don’t provide a position, each argument will be substituted in the same
order that the placeholders ({}
) appear.
"{:.3s} {:.2f}".format("Monday", 5.2423)
'Mon 5.24'
Or you can include the position to change the order in which they appear.
"{1:.2f} {0:.3s}".format("Monday", 5.2423)
'5.24 Mon'
Another advantage of .format()
is that anything not in curly braces is
interpreted literally.
"The price on {:.3s} is: ${:.2f}".format("Monday", 5.2423)
'The price on Mon is: $5.24'
You can also send keyword arguments to .format()
. Then, instead of using
position numbers, you use variable names.
blueprint = "The price on {day:.3s} is: ${cost:.2f}"
blueprint.format(
day="Monday",
cost=5.2423,
)
'The price on Mon is: $5.24'
Exercises#
(Format Email Address)
Given the following values:
user = "joe"
domain = "gmail"
extension = "com"
Use .format()
to print the string:
"joe@gmail.com"
Bonus: Write a format_email()
function that takes three arguments, name
,
domain
, and extension
and returns a formatted email address string.
Solution to Exercise 38 (Format Email Address)
Click to show
>>> "{user}@{domain}.{extension}".format(user="joe", domain="gmail", extension="com")
'joe@gmail.com'
Click to show: Bonus
def format_email(user, domain, extension):
return "{}@{}.{}".format(user, domain, extension)
print(format_email("joe", "gmail", "com"))
Click to show: Bonus alternate
def format_email(user, domain, extension):
return "{user}@{domain}.{extension}".format(user=user, domain=domain, extension=extension)
print(format_email("joe", "gmail", "com"))
f-strings#
Since we so frequently need to format strings, Python provides a shortcut
called f-strings, which have the letter f
immediately before the opening
single or double quote.
F-strings works just the same as .format()
, except variables are used instead
of keyword arguments.
day = "Monday"
cost = 5.2423
f"The price on {day:.3s} is: ${cost:.2f}"
'The price on Mon is: $5.24'
Exercise#
(Street Address)
Given the following values:
street = "1600 Pennsylvania Ave NW"
city = "Washington"
state = "DC"
zip = "20500"
Use an f-string to print the following:
1600 Pennsylvania Ave NW
Washington, DC 20500
Bonus: Write a format_address()
function that takes the arguments street
,
city
, state
and zip
and returns a formatted address string.
Solution to Exercise 39 (Street Address)
Click to show
>>> street = "1600 Pennsylvania Ave NW"
>>> city = "Washington"
>>> state = "DC"
>>> zip = "20500"
>>> print(f"{street}\n{city}, {state} {zip}")
1600 Pennsylvania Ave NW
Washington, DC 20500
Click to show: Bonus
1def format_address(street, city, state, zip):
2 return f"{street}\n{city}, {state} {zip}"
3
4print(format_address(
5 "1600 Pennsylvania Ave NW",
6 "Washington",
7 "DC",
8 "20500",
9))