10. Formatting Strings#
Before this notebook, we used string concatenation and multiple arguments to print() to format strings. Now, we will use string interpolation to put values into strings in various formats.
Python offers three different ways to format strings:
old style (all versions of Pythons) - see reference material if interested, not covered/tested
new style (Python 2.6 +)
f-strings (Python 3.6 +) - see reference material if interested, not covered/tested
The f-string style provides an easy convenience to put variables into strings but at the cost of requiring a literal (hard-coded) value to be used as the format string in the code. This limitation makes it harder to develop international-based applications.
This notebook directly prints the formatting results, but the formatted string could be assigned to a variable or used as an expression (e.g., as an argument to a function).
10.1. New style: {} and format()#
This format uses the form of format_string.format(data). Within each string are one or more placeholder fields identified by curly braces {}
that values will replace.
By default, the {} are replaced by data by matching order of the arguments to data - the indexing starts at zero. Addtionally, we can also specify name arguments to the placeholders.
1print("{}".format("Hello World!"))
2print("It was the {} of {}.".format("best","times"))
3print("It was the {1} of {0}.".format("times", "worst"))
4print("It was the {time} of {arg2}.\nIt was the {time} of {arg3} ...".format(time='age',arg2='wisdom',arg3="foolishness"))
Hello World!
It was the best of times.
It was the worst of times.
It was the age of wisdom.
It was the age of foolishness ...
We can also utilize a dictionary of key value pairs. The 0
in the code specifies the positional argument.
1d = {'time':'age', 'arg2':'wisdom', 'arg3':'foolishness'}
2print("It was the {0[time]} of {0[arg2]}.\nIt was the {0[time]} of {0[arg3]} ...".format(d))
It was the age of wisdom.
It was the age of foolishness ...
To format the values placed into the strings, you will need to apply special formatting codes. These codes follow this syntax: {[name]:[fill][alignment][sign][minwidth][group][.][maxchars]type}
An optional name that can either specify the position order or a named argument.
An initial colon (‘:’) that is required if any formatting codes exist.
An optional fill character (default ‘ ‘) to pad the value string if it is shorter than minwidth.
An optional alignment character:
‘<’ left (the default)
‘>’ right
‘^’ center
An optional sign for numbers. If
+
is specified, a plus symbol will be added to positive numbers. Negative numbers always have a minus sign.An optional minwidth.
An optional group that can contain either a
,
or an_
to separate thousands for numbersAn optional period (‘.’) to separate minwidth and maxchars if both values are defined. If only one is defined, maxchars is assumed.
An optional maxchars. If this is a float type, then this specifies the precision.
the type, which values are the same as the old style
Type |
Description |
---|---|
s |
string |
d |
integer |
x |
hexadecimal integer |
o |
octal integer |
f |
float |
e |
float in exponential format |
g |
decimal or exponential float |
Official Python Documentation for Format Strings
1alphabet = "abcdefghijklmnopqrstuvwxyz"
2print("123456789012345678901234567890")
3print("{}".format(alphabet))
4print("{:s}".format(alphabet))
5print("{:X<30s}".format(alphabet))
6print("{:X>30s}".format(alphabet))
7print("{:X^30s}".format(alphabet))
8print("{:30.5s}".format(alphabet))
9print("{:>30.5s}".format(alphabet))
123456789012345678901234567890
abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyzXXXX
XXXXabcdefghijklmnopqrstuvwxyz
XXabcdefghijklmnopqrstuvwxyzXX
abcde
abcde
1year = 1892
2print("123456789012345678901234567890")
3print("{:d}".format(year))
4print("{:20d}".format(year))
5print("{:+20d}".format(year))
6print("{:0>20d}".format(year)) # can't specify minwidth and max chars as we could in the old-style
7print("{:0^8d}".format(year))
8print("{:^20d}".format(year))
9print("{:x}".format(year))
10print("{:o}".format(year))
11print("{:x^8d}".format(year))
123456789012345678901234567890
1892
1892
+1892
00000000000000001892
00189200
1892
764
3544
xx1892xx
1gain = 64.98712
2print("123456789012345678901234567890")
3print("{:f}".format( gain))
4print("{:20f}".format( gain))
5print("{:+20f}".format( gain))
6print("{:020f}".format( gain))
7print("{:20.8f}".format( gain))
8print("{:20.2f}".format( gain))
9print("{:<20.6f}".format( gain))
123456789012345678901234567890
64.987120
64.987120
+64.987120
0000000000064.987120
64.98712000
64.99
64.987120
Notice in the above example, the default justification is left, unless minwidth or the precision is specified where the numbers become right justified.
You can use variables in the formatting placeholder by surrounding them with {}
. See below where we have used w and d.
1gain = 64.98712
2print("123456789012345678901234567890")
3print("{:{w}.{d}f}".format( gain, w=15,d=2))
4print("{:15.2f}".format( gain))
123456789012345678901234567890
64.99
64.99
10.2. Suggested LLM Prompts#
Explain the concept of new-style string formatting in Python, also known as the “str.format()” method. Discuss its advantages over older formatting techniques like %-formatting and string concatenation.
Describe the syntax for using placeholders in new-style string formatting. Provide examples of how to use positional arguments, keyword arguments, and complex field values.
Demonstrate how to format integers and floating-point numbers using the new-style string formatting. Explore options for specifying the minimum field width, alignment, padding characters, precision, and alternative forms (e.g., scientific notation).
Compare and contrast the different methods for string formatting in Python. Provide examples when each method should be used.
Discuss techniques for formatting strings using new-style formatting. Cover truncating long strings, padding with characters, aligning text in fields, and converting case. Provide examples of formatting strings for different purposes, such as generating reports or displaying user input.
Provide examples of how Python’s “new style” string formatting is used in real-world applications, such as generating reports, formatting log messages, or building user interfaces. Discuss best practices for choosing the appropriate formatting method based on the requirements and readability concerns. Avoid mention of “f-strings”.
10.3. Review Questions#
What is the syntax for using new-style string formatting in Python?
What is the difference between using positional arguments and keyword arguments in string formatting?
How do you insert a value into a string using the format() method?
10.4. Drill#
For each of the steps with formatting, you should use the new style formatting syntax to produce the correct string for display.
Define a variable
year
with a value of 2024Display the string “2024 is the current year”.
Display the string “xx2024xx”.
Display the year value as hex.
Display the string “0002024”.
Define a variable
pi
with a value of 3.14159.Display the string “3.1416 is an approxiamate value of pi”.
Display the string “xxx3.14xxx”.
Display the string “0003.14159”.
Display the string “ 3.14159000”.
10.5. Exercises#
Develop a business format letter with the following specifications:
It should be in a function
produce_letter
that takes any arguments needed to produce your letter.The function should return a formatted string.
The string should be a multi-line string.
You should perform at least 5 formatting substitutions.
Write function format_check_amount(value) that takes a float arguments and then returns a string in the format of \$***XX.XX, where the leading asterisks are used to make the length of the output 10 characters and the precision is two digits.
Write a function with the following declaration -
def print_receipt(subtotal, tax_rate, tip_rate)
That prints the following:
Subtotal: $ 10.00
Tax: $ 0.50
Tip: $ 2.00
==========
Total: $ 12.50
with the call: print_receipt(10.00, .05, .2)
Use formatting for all of the numbers and equal signs.