Mark Redd

8 - Formatted Strings

As you use the print function there will be times when you need to “fill in the blank” and you can do this with format statements. Also we will introduce a few more features in addition to these.

# format_strings.py

# We can print a comma-separated list
print("How much will this cost?", 23.00, "dollars")

# However, this is more readable and flexible 
# with a .format statement
print("How much will this cost? {} dollars.".format(23.0))

# The benefits of formatting become more
# apparent with more blanks to fill in.
print("Prices for cheese: "
    "${}/1 oz, ${}/5 oz, ${}/10 oz".format(1.23, 5.35, 9.84)
)

# Change the formatting order with indices in the braces
print("Would you like {2}, {0} or {1}?".format(
    "Brie", "Gouda", "Cheddar"
	)
)
# notice the formatting of code  in the previous two examples
# so each line of code stays short. Always use 4 spaces for 
# indents in Python.

# line up numbers and decimal places with format codes
print("""
Prices for cheese:
${:5.2f}/ 1 oz
${:5.2f}/ 5 oz
${:5.2f}/10 oz
""".format(1.23232, 5.3593, 9.84655))

Here is what should happen

(If needed, see Section 4 to review how to run a script.)

$ python format_strings.py
How much will this cost? 23.0 dollars
How much will this cost? 23.0 dollars.
Prices for cheese: $1.23/1 oz, $5.35/5 oz, $9.84/10 oz
Would you like Cheddar, Brie or Gouda?

Prices for cheese:
$ 1.23/ 1 oz
$ 5.36/ 5 oz
$ 9.85/10 oz

$

Formatting and the .format() method

We must understand a few things before understanding this code.

Format commands

Let’s look at each example of a .format statement one by one:

There are other formatting commands other than this but this is a good start to using formatting that will come up again and again. To review:

# formatting cheat sheet
print("{<identifier><command>:<format>}".format(arguments))

Hone Your Skills

print("No. " * 3)
print("No.","No.","No.")
print("{0} {0} {0}".format("No."))
print("{} {} {}".format("No.","No.","No."))
print("{0} ".format("No.") * 3)