Python. format of Function Explanation

  • 2021-12-11 08:24:57
  • OfStack

Call of directory format function call format of format function and its placeholder placeholder and parameter setting position/keyfill parameter align parameter sign parameter width parameter precision parameter precision-type parameter summary

Calling the format function

format functions can be called directly or formatted with placeholders in print functions.
Prior to **2.6**, placeholders were still using% as in other languages (such as C). However, in subsequent versions, the placeholder of format function is changed to {} (curly braces).

At present, four optimization purposes have been summarized:

1. Curly brace closure can realize more formatting and more powerful functions

2. Make your code more readable.

3. A single parameter can be output multiple times, and the order of parameters can be different

4. Regardless of the data type,% s can only replace the string type in the% method

Ok, going to the text, the use of format function will be divided into two parts.

1. The calling format of format function and its placeholder

2. Placeholder format and parameter setting

ps: When introducing, each content will be slightly interspersed, in fact, it is for easier understanding ~

The calling format of format function and its placeholder

format functions can be called directly, such as in shell

Example 1


>>>'{} {}'.format('hello','world')       # Placeholders do not specify order 
'hello world'
>>>'{0} {1}'.format('hello','world')       # Placeholder making order 
'hello world'
>>>'{1} {0}'.format('hello','world')       # Change 1 Try in the next order 
'world hello'
 

Our more common way is to put it into the print () function for formatting output

Example 2


print('{} Get S8 Champion '.format('IG')
# Results: 
#IG Get S8 Champion 

Placeholders and parameter settings

In Part 1, I briefly introduced two ways to call the format function. It can be clearly found that 1 parameters can also be input in placeholders to set the parameters of formatted output. The order and setting of various parameters in placeholders are introduced in detail below.

The format of each parameter in the placeholder is as follows

Example 3 (pseudocode)


'{position/key:fill,align,sign,width,precision,type}'.format(...)

position/key

position/key specifies which value to call from the parameters of the format function at the placeholder. position is easy to understand. For example, the latter two calls introduced in Example 1 above specify the order in which the two parameters hello and world in format are called in the placeholder. Note that this order is calculated from '0' in array sorting. Of course, you can also use key-value pairs. For example, in Example 4 below:

Example 4


print(
    'the championship of the S8 is {S8}, and for S9, it\'s {S9}.'.format(S8='IG',S9='FPX'))
# Results: the championship of the S8 is IG, and for S9, it'FPX.

Some writing partners may have to ask, is the use of key value pairs (dictionaries) good here? I don't feel as fast as filling in a number.

Let's look at the following code:

Example 5:


dic={'S8':'IG','S9':'FPX'}
print(
    'the championship of the S8 is {S8}, and for S9, it\'s {S9}.'.format(**dic))
# Results: the championship of the S8 is IG, and for S9, it'FPX.

In Example 5, there are some places that need special explanation. First of all, if you want to call the dictionary in parentheses of format, remember to add * * before the dictionary name, which is the function call method of the dictionary! As you can see from Example 5, we don't need to list dictionaries specifically in format, but we can call previously defined dictionaries, which makes it have the advantage of repeated calls. Imagine the difference between this 1 point, which% method can't do.

You can also fill it in the form of an array, as shown in Example 6:

Example 6:


names=['hilary','vergil','nero']
places=['chengdu','shijiazhuang','tokyo']
print(
    'Hi, {names[0]}. I am {names[1]} and this is {names[2]}.'.format(names=names)
    #Hi, hilary. I am vergil and this is nero.

The parameter at the first position is also the only parameter before the colon. I believe everyone will understand it.

The following parameters are all juxtaposed, and we explain them one by one. First, make it clear how these parameters are juxtaposed or separated.

That is no separation, yes, the following parameters, which you need to define, just write them down in order, without adding commas or spaces to separate them. You may think, isn't this ambiguous? I thought about it when I was studying, and the fact is that when developers edit function logic, they combine the settings of these parameters with symbols or numbers that will not cause any ambiguity, which will be found when you use them.

fill Parameters

The fill parameter is used to specify the filler, and the default value is a space. Practical experience is that this parameter is rarely used in scenarios, except in scenarios such as separating numbers by 3 digits and 1 comma according to the international common use.

Example 7:


>>> print('{:,}'.format(12345678))
12,345,678

align Parameters

The align parameter is used to format the alignment of text. When you fill in the width, this parameter has a great effect. Of course, if you seamlessly insert a formatted text in a sentence, the setting of this parameter is not meaningful.

> < ^
右对齐 左对齐 居中对齐

Example 8:

Run the following code in shell (the number 310 in the code denotes the width to widen the overall width to show the alignment effect, and the usage of the width will be mentioned later)


>>> print('{:<30}'.format('pos'))
pos
>>> print('{:>30}'.format('pos'))
                           pos
>>> print('{:^30}'.format('pos'))
             pos

sign Parameters

The sign parameter is used to specify whether the sign is preserved, which works for numbers in format.

+ - SPACE
保留正负号 仅保留负号 正数留空,负数保留负号

Example 9:


>>> print('{0:+} {0:-} {0: }'.format(123))
+123 123  123
>>> print('{0:+} {0:-} {0: }'.format(-123))
-123 -123 -123

ps: Note that the last one in the running result of line 1 keeps one space

width Parameters

The width parameter controls the length of the output. After my test, the length is the minimum length, that is, when the set width parameter is less than the value called in format, it does not take effect; When the set value is large, it will be filled with space (default) or zero. If you want to fill with 0, you need to add 0 before width. The use of width parameters is shown in Example 10. The width parameter is also used when showing the alignment parameters in Example 8, so it can be seen that alignment has an impact on our filling method, and the specific impact is also given in Example 10.

Example 10:


print('{0:12} {0:05} {0:2}'.format(123)) # In order 12 Bit width space filling, 5 Bit width 0 Fill, 2 Bit width 
# Results: 
#         123 00123 123
print('{0:<012},{0:>012},{0:^012} '.format(123))
# Results: 
#123000000000,000000000123,000012300000 
print('{0:^012},{1:^012},{0:^011},{1:^011} '.format(123,1234))
# Results: 
#000012300000,000012340000,00001230000,00012340000

It can be seen that the filling of spaces is also displayed with alignment differences, but the filling of zeros often changes the representation of our numbers, so we should pay attention when using them. Another thing to note is that when the parity of your total width and the effective width of the data is different, the way of center alignment will be different, which is what the code in Line 3 of Example 10 wants to mean. It can be seen that when the odd and even times are different, it always leans to the left 1 bit alignment.

precision Parameters

And% methods, such as%. 3f for preserving 3 decimal places, and ". preserving significant digits (f)" for data accuracy. If f is added, it means preserving decimal places, and if it is not added, it means preserving significant digits. Example 11 shows this difference well.

Example 11:


print('{} Get S8 Champion '.format('IG')
# Results: 
#IG Get S8 Champion 
0

In fact, my friends should notice that f and% here are actually the content controlled by type parameters after precision parameters-data types. Therefore, we briefly introduce the precision, and introduce the joint parameters of precision-type parameters in detail, because they are strongly related.

precision-type parameters

First, introduce all the type parameters, as shown in the following table:

type参数 含义
默认 10进制整数 123
f 浮点数 123.123
% 百分比格式 12312.3%
e 指数形式 1.2e01
- d 10进制整数 123
进制转换 10进制 123
b 2进制 1101111
o 8进制 157
x 106进制 6f
#x 小写表示的106进制 0x6f
#X 大写表示的106进制 0X6F
c 字符,打印前转换为Unicode代码 ‘123'

This article is a summary of learning, citing 1 piece of code, there is a reference number in the article, and the reference link is placed below:

https://www.ofstack.com/article/226500.htm

Summarize

This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!


Related articles: