Python formatted string literal | is the official document called “beautiful” output format

This article refers to the INPUT/Output – Python 3.7.10 documentation. Let’s start by stating our lab environment.

❯ python --version
Python 3.7.0
Copy the code

Example: Requirements created by the scenario

We need to feedback the calculation result to the user on the console (for example, AOE is 0.82), so we need to write print logic. The statement describing the result of the calculation is dead (AOE value is), but the number is alive (0.82). We want to concatenate the results into a statement that describes the structure. Novices may use string concatenation (string “addition” +).

val_dict = {
    'AOE': 0.8200001.'wcb': 13423431.'p': 0.0314
}

print(AOE value is "" + str(val_dict['AOE']) + ", WCB value is" + str(val_dict['wcb']))
if val_dict['p'] < 0.05: print('Reject the null hypothesis')
else: print('Acceptance null hypothesis')
Copy the code

Output:

AOE value is 0.8200001, WCB value is 13423431 reject null hypothesisCopy the code

We will introduce a formatting method that is more elegant, both written and readable.

In addition, we will solve problems such as decimal places and scientific notation that string concatenation cannot solve automatically.

Format string literals

Official documentation: To use formatted string literals, precede the opening or triple quotation marks of the string with an f or f. In this string, you can write Python expressions between {and} characters that can refer to variables or literals.

It’s a little confusing, but it’s best to look at examples.

Let’s change the code above.

print(F "AOE value is{val_dict['AOE']}, WCB value is{val_dict['wcb']}")
print(f"{'Reject the null hypothesis' if val_dict['p'] < 0.05 else 'Acceptance null hypothesis'}")
Copy the code

Output:

AOE value is 0.8200001, WCB value is 13423431 reject null hypothesisCopy the code

There’s nothing wrong with it. It’s exactly the same as before. But we’re embedding the “live” variable directly into the “dead” sentence.

F “{}” {} curly braces can be used to put variables and expressions.

To see more uses of the above example, do simple operations in {} braces, or use special formatting syntax to preserve decimals and convert them to scientific notation.

print(F "AOE value is{val_dict['AOE'] * 100}%, WCB value is{val_dict['wcb'] :E}")
print(f"{'Reject the null hypothesis' if val_dict['p'] < 0.05 else 'Acceptance null hypothesis'}")
Copy the code

Output:

AOE value is 82.00001%, WCB value is 1.342343E+07 reject null hypothesisCopy the code

Notice that we used the special syntax {val_dict[‘ WCB ‘] :E} above, where :E means to convert the number val_dict[‘ WCB ‘] into scientific notation.

Like :E, we have more. In Python, the name is Format Specification Mini Language.

We can directly use :.2% to mean “make the number a percentage % and keep two decimal places (.2)”.

print(F "AOE value is{val_dict['AOE'] :2.%}%, WCB value is{val_dict['wcb'] :E}")
print(f"{'Reject the null hypothesis' if val_dict['p'] < 0.05 else 'Acceptance null hypothesis'}")
Copy the code

Output:

AOE value is 82.00%%, WCB value is 1.342343E+07 reject null hypothesisCopy the code

{val_dict[‘AOE’] * 100}%

More examples

For other uses, see Python’s String format examples. Let’s create our own scenario here: print a table.

table = {
    'Tom': [31.32.314.31.423.].'Jerry': [1.. 41.313.123].'Paul': [7.4..53.45754.]}def print_table(t) :
    print('| name | attr | feat | gest | dest |')
    print('| -- -- -- -- -- -- -- - | -- -- -- -- -- -- -- - | -- -- -- -- -- -- -- - | -- -- -- -- -- -- -- - | -- -- -- -- -- -- -- - |')
    for name, vals in table.items():
        print(f'|{name :_^8}|{vals[0] : ^8}|{vals[1] : >6.2f}  |{vals[2] : ^8}|{vals[3] : >8.3f}| ')

print_table(table)
Copy the code

Output:

| name | attr | feat | gest | dest | | -- -- -- -- -- -- -- - | -- -- -- -- -- -- -- - | -- -- -- -- -- -- -- - | -- -- -- -- -- -- -- - | -- -- -- -- -- -- -- - | | __Tom___ | | | | | 0.423 31 32.31 31 | _Jerry__ | 1 | 0.41 123.000 | | 313 | | __Paul__ | | | | | 0.458 53 0.40 7Copy the code

Above:

  • Our data is intableData is stored in it
  • inprint_tableSaves the logic for printing data
    • f{name :_^8},^In the middle,8Represents the length of8._Said to fill_(Default padding)
    • f} {vals [1] : > 6.2 f,> 6Represents the length of6And on the right,.2fRepresents as a decimal and is reserved2

In addition to the official documentation, the Python formatting functions in the Rookie tutorial are also good Chinese resources.

In the future, you can use the keyword Python + in the search engine to format the output.

I am Xiaopai, welcome to add my wechat PiperLHJ reprint communication.