What are the secret f-string skills that Python users don't know?
This article shows you what are the secret skills of f-string that Python users do not know. The content is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.
F-string must have been used by many Python users basically. as a feature introduced at the beginning of the Python3.6 version, we can more easily embed custom content into strings, but the real features contained in f-string are much richer than most users know. Today, let's get them together.
The most basic usage
The most basic use of f-string is simple, as shown in the following example, filling in the string of the prefix f directly into {} the value, variable, or evaluation expression to be embedded:
Figure 1 "self-recording expression"
Starting with the Python3.8 version, a "self-recording expression" has been introduced for f-string, allowing us to quickly output some evaluation expressions as follows:
Figure 2 "Multi-line f-string"
By wrapping parentheses in the outermost layer, we can write multiple lines of f-string very flexibly as follows:
Figure 3 "formatting dates in f-string"
For date-type variables, we can refer to the following ways to quickly format them directly in f-string:
Figure 4 "controlling floating-point accuracy"
In f-string, we can flexibly control the number of decimal places for floating-point numbers in the following ways:
Figure 5 "standardized display width"
When we need to limit the minimum display width of f-string prints, such as printing out a similar table structure, we can refer to the following example:
Figure 6 "modify to left alignment"
F-string defaults to right alignment, as in the example above, but we can use it like this