Reader small image

You're reading from  Scientific Computing with Python - Second Edition

Product typeBook
Published inJul 2021
Reading LevelIntermediate
PublisherPackt
ISBN-139781838822323
Edition2nd Edition
Languages
Right arrow
Authors (3):
Claus Führer
Claus Führer
author image
Claus Führer

Claus Führer is a professor of scientific computations at Lund University, Sweden. He has an extensive teaching record that includes intensive programming courses in numerical analysis and engineering mathematics across various levels in many different countries and teaching environments. Claus also develops numerical software in research collaboration with industry and received Lund University's Faculty of Engineering Best Teacher Award in 2016.
Read more about Claus Führer

View More author details
Right arrow

2.4.3 String formatting

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}'.

Previous PageNext Page
You have been reading a chapter from
Scientific Computing with Python - Second Edition
Published in: Jul 2021Publisher: PacktISBN-13: 9781838822323
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (3)

author image
Claus Führer

Claus Führer is a professor of scientific computations at Lund University, Sweden. He has an extensive teaching record that includes intensive programming courses in numerical analysis and engineering mathematics across various levels in many different countries and teaching environments. Claus also develops numerical software in research collaboration with industry and received Lund University's Faculty of Engineering Best Teacher Award in 2016.
Read more about Claus Führer