11. Formatting Strings - New Style#
f-strings (see 09-FormattingStrings.ipynb) are now the recommended approach. This notebook covers the .format() method, which remains necessary when using the gettext module for internationalization or when working with legacy code.
Python offers three approaches to format strings:
f-strings (Python 3.6+) — recommended; see 09-FormattingStrings.ipynb
new style (Python 2.6+) —
.format()method — this notebookold style (all versions) —
%operator — see 09.b-FormattingStrings-OldStyle.ipynb
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).
11.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. Additionally, 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, minwidth 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, Numbers are right-justified by default; strings are left-justified by default. Specifying a width does not change these defaults.
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
11.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.