Core Python / String Formatting#
Review Questions#
What is the syntax for using new-style string formatting in Python?
To format a string, call the
format()
function on that string."{:d}".format(10)
The formatting codes have this specification:
{[name]:[fill][alignment][sign][minwidth][group][.][maxchars]type}
You are not expected to memorize the specification or the various codes, but with a reference card, you should be comfortable formatting strings.
What is the difference between using positional arguments and keyword arguments in string formatting?
Immediately after the left curly brace
{
, an optional positional or name argument may be specified. We can then use that position or name to map to variables (expressions) specified in the arguments toformat()
.How do you insert a value into a string using the format() method?
To insert a value into a string using the format() method, you use replacement fields within the string, denoted by curly braces {}. The values to be inserted are provided as arguments to the format() method.
name = "Alice" age = 25 formatted_string = "My name is {} and I'm {} years old.".format(name, age) print(formatted_string)
Drill Steps#
year = 2024
print("{:d} is the current year".format(year))
print("{:x^8d}".format(year))
print("{:x}".format(year))
print("{:0>7d}".format(year))
pi = 3.14159
print("{:.4f} is an approxiamate value of pi".format(pi))
print("{:x^10.2f}".format(pi))
print("{:0>10.5f}".format(pi))
print("{:12.8f}".format(pi))