String formatting is the process of inserting values into a given string and determining the way in which they are displayed. This can be done in various ways. We first describe the related string method, format, and the more modern alternative, the so-called f-string.
Here is an example regarding the use of the format method:
course_code = "NUMA01"
print("Course code: {}".format(course_code)) # Course code: NUMA01
And here is an example of the variant by using an f-string:
course_code = "NUMA01"
print(f"Course code: {course_code}") # Course code: NUMA01
The function format is a string method; it scans the string for the occurrence of placeholders, which are enclosed by curly brackets. These placeholders are replaced in a way specified by the argument of the format method. How they are replaced depends on the format specification defined in each {} pair. Format specifications are indicated by a colon, ":", as their prefix.
The format method offers a range of possibilities to customize the formatting of objects depending on their types. Of particular use in scientific computing are the formatting specifiers for the float type. You may choose either the standard fixed-point notation with {:f} or the exponential notation with {:e}:
quantity = 33.45
print("{:f}".format(quantity)) # 33.450000
print("{:1.1f}".format(quantity)) # 33.5
print("{:.2e}".format(quantity)) # 3.35e+01
Similarly, format specifiers can be used also in f-strings:
quantity = 33.45
print(f"{quantity:1.1f}") # 33.5
The format specifiers allow specifying the rounding precision (digits following the decimal point in the representation). Also, the total number of symbols, including leading blanks, to represent the number can be set.
In this example, the name of the object that gets its value inserted is given as an argument to the format method. The first {} pair is replaced by the first argument, and the following pairs by the subsequent arguments. Alternatively, it may also be convenient to use the key-value syntax:
print("{name} {value:.1f}".format(name="quantity",value=quantity))
# prints "quantity 33.5"
Here, two values are processed – a string name without a format specifier, and a float value that is printed in fixed-point notation with one digit after the decimal point. (Refer to the complete reference documentation for more details on string formatting.)
Braces in the string
Sometimes, a string might contain a pair of curly braces, which should not be considered as placeholders for a format method. In that case, double braces are used:
r"we {} in LaTeX \begin{{equation}}".format('like')
This returns the following string: 'we like in LaTeX \\begin{equation}'.