"Learning Python with You Hand in Hand" 11-Formatted Output of Strings

​In the last article "Learning Python with You Hand in Hand" 10-String Functions , we learned the function processing methods of strings. Coupled with the slicing, indexing, and operations learned before, it can be said that various common operations of strings have been touched. In this article, we will learn how to format strings together.

Why is it called formatted input? This corresponds to our normal output.

The output method we learned before is to use the print() function to print the string. What the string looks like and what the printed result looks like, this is the general output method.

What about formatted output? There are two main features:

One is that the output result can be adjusted according to our needs or the results of the operation through the form of placeholders.

Consider the simplest example: roll a dice and output the result of the throw. Because it is impossible for us to know the result of the throw in advance, we cannot directly output it with the print() function. At this time, you need to use the placeholder formatted output method. First leave a place for the part that may change with the result, then fill in this place according to the result, and finally print. E.g:

In [1]: import random

In [2]: result = random.randint(1, 7)   # 随机产生1至6的整数
       print("投掷的结果是:{}。".format(result))
Out[2]: 投掷的结果是:5。

Among them, the role of import random is to import the random function module, so that the function that generates random numbers can be run later.

random.randint(1, 7) is a function used to randomly generate integers between 1 and 7, left closed and open, so the result includes 1 but not 7, which means 1 to 6. This function can only be run after importing the random function module. If you run it without importing it, an error will be reported.

(About in the example, we used the content that has not been mentioned for the sake of demonstration. We will briefly talk about it in the article. You can find out in advance. There will be more systematic explanations in future articles.)

In addition, the string in the print() function obviously has an extra {}. But this {} will not be printed, it is just a placeholder, and the printed content is determined by the value in () after format. In the example, the value in () is a random value from 1 to 6 represented by the variable result. The value in the example is 5, so put 5 in the placeholder {} and output it.

This is just an example to illustrate the characteristics of formatted output. It doesn't matter if you don't understand, there will be a detailed explanation later.

The second is to output according to the format or printing effect we expect.

This kind of formatting mainly refers to the formatting of numbers, such as changing the number of digits output, output in accordance with scientific notation, or changing the alignment of numbers, using 0 or spaces to fill the digits, and so on. E.g:

In [3]: a= 123.456789
        print('%.3f'%a)   # %.3f的意思是保留小数点后3位进行输出,同时也是一个占位符,把后面%a代表的值在这个位置输出
Out[3]: 123.457
​
In [4]: a= 123.456789
        print('%010.3f'%a)   # %010.3f的意思是输出的总宽度为10(这个10是小数点前面的10),保留小数点后3位,不足的位置用0补齐(这个0是%右侧的0),进行输出,也同样起到占位符的作用
Out[4]: 000123.457

% Is the identifier for formatting the output result. The content after% is the requirement for formatting output. It is expressed by some numbers, letters and symbols. It may seem more complicated. We will analyze it in detail below.

For the first form of placeholder, we will often use it in the future. And whether it is necessary to have a second formatted output form for numbers, you may not understand it, this may not be imagined until it is needed. In short, Python provides such a way to format and output numbers in case of emergency.

In the following, the formatting output method will be explained in detail.

There are three formatting output methods provided by Python, namely the format() function, the f method and the% formatting method in the example just now. One of the most commonly used and most professional usage is the format() function. You can learn more about the other content and come back when you need it.

format() function

1. Format parameters

The format parameter corresponds to the placeholder {} in the string to be output, and they are not limited in number. As long as necessary, an unlimited number of placeholders and corresponding parameters can be added. Just considering the readability of the code, it is not recommended to use too many placeholders and parameters.

By default, the number of parameters and the number of placeholders are the same. There are as many parameters as there are placeholders. The positions are also in a one-to-one correspondence from left to right, that is, the first placeholder is filled with the first parameter, the second placeholder is filled with the second parameter, and so on.

In [5]: print("这篇文章属于{}系列,是系列文章中的第{}篇,副标题是{}。".format('《手把手陪您学Python》', '11', '字符串的格式化输出'))   # 按从左往右的顺序一一对应
Out[5]: 这篇文章属于《手把手陪您学Python》系列,是系列文章中的第11篇,副标题是字符串的格式化输出。

In addition to the default method, there are 4 ways to specify the parameter order or fill placeholders:

a. Use location index

The position index is the same as the string index method we introduced before (so at that time, this method or principle is very important. For details, please refer to the article "Learning Python with You" 7-String Index ), as long as the format () Each parameter of is understood as each character in the string.

The first parameter from left to right in format is position 0, the second parameter is position 1, and so on. The same goes for right to left, the first parameter (that is, the last parameter from left to right) is position -1, and the second parameter is position -2.

By default, there is no need to put characters in {}. When using the position index, you need to write the position index of the parameter to be filled in {}, which can be used out of order or repeated.

It is easy to understand if you look at the example.

In [6]: print("本文作者:{0},性别:{1},爱好:{2},笔名:{0}。".format('mnpy', '男', 'Python'))   # 根据占位符中的位置索引,取参数中对应位置的值进行填充
Out[6]: 本文作者:mnpy,性别:男,爱好:Python,笔名:mnpy。

b, use variable naming

The advantage of using variable naming is that it is very intuitive, and it is clear which placeholder corresponds to which parameter. Of course, it can also be used out of order or repeated filling.

In [7]: print("本文作者:{name},性别:{gender},爱好:{hobby},笔名:{name}。".format(name='mnpy', gender='男', hobby='Python'))   # 根据占位符中的变量,取参数中相同变量的值进行填充
Out[7]: 本文作者:mnpy,性别:男,爱好:Python,笔名:mnpy。

c. Use a dictionary

The dictionary is a data structure we will talk about later. If you don't understand, you can skip this one first.

The way of using a dictionary is similar to using variable names. The difference is that when using a dictionary, the value of each variable is set in the dictionary, and the parameter of format is just a dictionary type object.

In [8]: info = {'name': 'mnpy',  'gender': '男',  'hobby': 'Python'}
        print("本文作者:{name},性别:{gender},爱好:{hobby},笔名:{name}。".format(**info))   # 根据占位符中的变量,取字典中相同键名对应的值进行填充
Out[8]: 本文作者:mnpy,性别:男,爱好:Python,笔名:mnpy。

Note: There are two * before the format parameter, which cannot be omitted.

d. Use list

The list is also a data structure we will talk about later, if you don't understand it, you can skip it first.

The way of using the list is a bit cumbersome, and it needs to use the position index twice. The first position index is the position of the parameter in the index format(). If the parameter is a list, another position index must be nested, and the index is the list The position of the element.

In [9]: info = ['mnpy', '男', 'Python']
        print("本文作者:{1[0]},性别:{1[1]},爱好:{1[2]},笔名:{0}。".format('mnpy', info))   # {}里第一个数字是对format参数的位置索引,[]里的数字是对列表元素的位置索引
Out[9]: 本文作者:mnpy,性别:男,爱好:Python,笔名:mnpy。

Speaking of this, everyone can basically master the basic usage of the format() function, and the most important content in the formatted output of a string has been learned. The following content may be a little difficult, and it is not used much at the beginning stage, so you can learn according to your needs.

2. Number formatting of format

Just now we learned how to use the format() function to fill the position of the placeholder to format the output method. Next, we will learn how to format the output number, that is, let the number be output in the format we require.

The number formatting of format is realized by adding a ":" in the placeholder {}, and then writing the relevant symbols of the formatting output method. There are 8 types of this formatted output method:

a, accuracy

Precision mainly refers to keeping to a few digits after the decimal point in accordance with the rules of rounding, using the form of {:.nf} to achieve, where n represents the reserved digits and needs to be replaced by a number. {:.0f} means no decimals are kept, {:.6f} means keep up to 6 decimal places.

f stands for float, which is the meaning of decimals, and corresponds to the d representing integers that we will talk about later. If the parameter in format is a decimal, f must be used in {}; if the parameter in format is an integer, either d or f can be used in {}. Because the precision problem is only related to decimals, f is used here.

In [10]: print("如果不保留小数,π的值显示为:{:.0f}。".format(3.1415926))
Out[10]: 如果不保留小数,π的值显示为:3。
​
In [11]: print("如果保留三位小数,π的值显示为:{:.3f}。".format(3.1415926))   # 四舍五入
Out[11]: 如果保留三位小数,π的值显示为:3.142。
​
In [12]: print("如果保留三位小数,100的值显示为:{:.3f}。".format(100))   # format参数为整数,也可以使用f,根据精度,小数点后自动补0
Out[12]: 如果保留三位小数,100的值显示为:100.000。

When the precision value is omitted and only f is written, it is reserved to 6 digits after the decimal point by default, which is the same as {:.6f}. Even if the format parameter is an integer, it is retained to 6 digits after the decimal point.

In [13]: print("如果省略精度值,π的值显示为:{:f}。".format(3.1415926))
Out[13]: 如果省略精度值,π的值显示为:3.141593。
​
In [14]: print("如果省略精度值,100的值显示为:{:f}。".format(100))
Out[14]: 如果省略精度值,100的值显示为:100.000000。
​
In [15]: print("如果省略精度值,100的值显示为:{:d}。".format(100))   # format参数为整数,忽略精度使用d,没有任何效果
Out[15]: 如果省略精度值,100的值显示为:100。

b. Alignment, width and padding

The reason why these three are discussed together is because they work at the same time.

Alignment refers to the alignment of the output numbers. The three symbols ^, <,> represent center alignment, left alignment, and right alignment respectively.

The width is the minimum number of digits of the digital output, expressed in numbers, and written on the right side of the alignment symbol.

The width includes the number of characters in the whole number, such as integer, decimal point, and decimal place. For example, the number of digits in 3.1415926 is 9. If the number of digits is greater than the specified width, it will be output according to the number of digits; if the number of digits is less than the specified width, it will be output according to the specified width. The insufficient number of digits will use the specified symbol according to the alignment method filling.

The filling symbol is written in front of the alignment symbol. If the filling symbol is not specified, it will be filled with spaces by default. The fill symbol can only be one character, not multiple characters, or a string.

In [16]: print("左对齐、宽度10、填充XD,π的值显示为:{:XD<10f}。".format(3.1415926))   # 填充值为多个字符时报错
Out[16]: ---------------------------------------------------------------------------
         ValueError                                Traceback (most recent call last)
         <ipython-input-24-43e3ac9e0166> in <module>
         ----> 1 print("左对齐、宽度10、填充XD,π的值显示为:{:XD<10f}。".format(3.1415926))   # 填充值为多个字符时报错
​
         ValueError: Invalid format specifier
​
In [17]: print("左对齐、宽度10、填充X,π的值显示为:{:'X'<10f}。".format(3.1415926))   # 填充值为字符串时报错
Out[17]: --------------------------------------------------------------------------
         ValueError                                Traceback (most recent call last)
         <ipython-input-25-7a00814795e8> in <module>
         ----> 1 print("左对齐、宽度10、填充X,π的值显示为:{:'X'<10f}。".format(3.1415926))   # 填充值为字符串时报错
         
         ValueError: Invalid format specifier

The precision is written after the width, and it still represents a few digits after the decimal point. If the precision value is omitted, it is retained to 6 digits after the decimal point by default.

As you can see from the example below, the padding value is only one character. The precision value is omitted, and 6 digits after the decimal point are reserved by default, so the width of the number is 8. The specified width is 12 and the difference is 4 bits. Because it is left-justified, the padding symbol X is used on the far right to fill in the difference of 4 bits.

In [18]: print("左对齐、宽度12、填充X、默认精度6,π的值显示为:{:X<12f}。".format(3.1415926))
Out[18]: 左对齐、宽度12、填充X、默认精度6,π的值显示为:3.141593XXXX。

The above is the most complicated part of the digital formatting rules of format. The following will demonstrate the above rules with some examples and notes. Since the padding value uses the default space, the effect will not be visible; if the padding value is 0, the number itself will be misinterpreted, so the padding value in the example is set to X.

In [19]: print("右对齐、宽度12、填充X、默认精度6,π的值显示为:{:X>12f}。".format(3.1415926))   # 右对齐,前面填充
Out[19]: 右对齐、宽度12、填充X、默认精度6,π的值显示为:XXXX3.141593。
​
In [20]: print("居中对齐、宽度12、填充X、默认精度6,π的值显示为:{:X^12f}。".format(3.1415926))   # 居中对齐,前面平均填充
Out[20]: 居中对齐、宽度12、填充X、默认精度6,π的值显示为:XX3.141593XX。
​
In [21]: print("居中对齐、宽度11、填充X、默认精度6,π的值显示为:{:X^11f}。".format(3.1415926))   # 居中对齐,填充符无法平均分时,左边的填充符少1位
Out[21]: 居中对齐、宽度11、填充X、默认精度6,π的值显示为:X3.141593XX。
​
In [22]: print("左对齐、宽度5、填充X、默认精度6,π的值显示为:{:X<5f}。".format(3.1415926))   # 指定宽度5小于数字宽度8,按照数字宽度输出
Out[22]: 左对齐、宽度5、填充X、默认精度6,π的值显示为:3.141593。
​
In [23]: print("左对齐、宽度5、填充X、精度2,π的值显示为:{:X<5.2f}。".format(3.1415926))   # 指定宽度5大于数字宽度4,左对齐,右边填充
Out[23]: 左对齐、宽度5、填充X、精度2,π的值显示为:3.14X。
​
In [24]: print("左对齐、宽度12、填充X、整数值标识符d,100显示为:{:X<12d}。".format(100))   # format参数为整数,指定宽度12大于数字宽度3,左对齐,右边填充
Out[24]: 左对齐、宽度12、填充X、整数值标识符d,100显示为:100XXXXXXXXX。
​
In [25]: print("左对齐、宽度12、填充X、小数值标识符f,100显示为:{:X<12f}。".format(100))   # format参数为整数,精度默认小数点后6位,指定宽度12大于数字宽度10,左对齐,右边填充
Out[25]: 左对齐、宽度12、填充X、小数值标识符f,100显示为:100.000000XX。

The above example basically traverses the various changes in accuracy, alignment, width and padding. If you can accurately predict the result before the program runs, it means that you have mastered the most difficult and most confusing part of number formatting. The method is very easy.

c, sign

There are three ways to identify the sign.

The default is not to write the sign identifier, just like our usual habits, positive numbers do not display +, negative numbers display -.

When using the + identifier, positive numbers display +, and negative numbers remain unchanged or -.

When using a space identifier, positive numbers do not display +, but a character position is left blank, just like a space is output, negative numbers still display -.

Let us see through examples.

In [26]: print("采用默认值,正数100显示为:{:d},负数-100显示为:{:d}。".format(100, -100))
Out[26]: 采用默认值,正数100显示为:100,负数-100显示为:-100。
​
In [27]: print("使用+标识符,正数100显示为:{:+d},负数-100显示为:{:+d}。".format(100, -100))
Out[27]: 使用+标识符,正数100显示为:+100,负数-100显示为:-100。
​
In [28]: print("使用空格标识符,正数100显示为:{: d},负数-100显示为:{: d}。".format(100, -100))
Out[28]: 使用空格标识符,正数100显示为:100,负数-100显示为:-100。

If used together with precision, alignment, width, and padding, the sign identifier can only be placed in the middle of the alignment symbol and width, and an error will be reported in other positions. When calculating the width, +- signs and spaces are also counted in the number of digits.

In [29]: print("同时使用+标识符、左对齐、宽度10、填充X、精度2,正数100显示为:{:X<+10.2f},负数-100显示为:{:X<+10.2f}。".format(100, -100))
Out[29]: 同时使用+标识符、左对齐、宽度10、填充X、精度2,正数100显示为:+100.00XXX,负数-100显示为:-100.00XXX。
​
In [30]: print("同时使用空格标识符、左对齐、宽度10、填充X、精度2,正数100显示为:{:X< 10.2f},负数-100显示为:{:X< 10.2f}。".format(100, -100))
Out[30]: 同时使用空格标识符、左对齐、宽度10、填充X、精度2,正数100显示为:100.00XXX,负数-100显示为:-100.00XXX。

d, thousands comma separated

Thousands are separated by commas using "," as the identifier, and numbers are separated by "," to separate the thousands.

If used with precision, alignment, width, padding, and sign, the thousands separator can only be placed after the width. When calculating the width, each comma separator is counted as one digit.

In [31]: print("1000000按照千位分隔符显示为:{:,}。".format(1000000))
Out[31]: 1000000按照千位分隔符显示为:1,000,000。
​
In [32]: print("1000000同时按照多种格式化条件显示为:{:X<+15,.2f}。".format(1000000))   # 千位分隔标识符只能放在宽度的后面
Out[32]: 1000000同时按照多种格式化条件显示为:+1,000,000.00XX。

e, percentage

The percentage format uses% as an identifier, and converts the number into a percentage value for output.

If you do not specify the precision, the default is to keep 6 digits after the decimal point. If you want to keep other digits after the decimal point, you need to specify the precision. If used with precision, alignment, width, padding, sign, and thousands separator, the percentage identifier can only be placed at the end and cannot contain f or d. When calculating the width,% also occupies a number of digits.

f, scientific notation

Scientific notation uses e as an identifier and converts numbers into scientific notation for output.

The output method and percentage of scientific notation are the same except for the identifier. If you do not specify the precision, it will be output by default to 6 digits after the decimal point. If you want to keep other digits after the decimal point, you need to specify the precision. If used together with precision, alignment, width, padding, sign, and thousands separator, the scientific notation identifier can only be placed at the end, and cannot contain f or d. When calculating the width, each of e+ occupies one digit.

In [35]: print("1000000按照科学计数法显示为:{:e}。".format(1000000))
Out[35]: 1000000按照科学计数法显示为:1.000000e+06。
​
In [36]: print("1000000同时按照多种格式化条件显示为:{:X<+15,.2e}。".format(1000000))   # 科学计数法标识符只能放在最后,且不能包含f和d的标识符
Out[36]: 1000000同时按照多种格式化条件显示为:+1.00e+06XXXXXX。

g, base conversion

Base conversion refers to converting the decimal system we usually use into binary, octal, hexadecimal, etc. Because it is rarely used, just give a few examples.

In [37]: print("11转换成二进制显示为:{:b}。".format(11))
Out[37]: 11转换成二进制显示为:1011。
​
In [38]: print("11转换成八进制显示为:{:o}。".format(11))
Out[38]: 11转换成八进制显示为:13。
​
In [39]: print("11转换成十进制显示为:{:d}。".format(11))
Out[39]: 11转换成十进制显示为:11。
​
In [40]: print("11转换成十六进制显示为:{:x}。".format(11))
Out[40]: 11转换成十六进制显示为:b。
​
In [41]: print("11转换成十六进制显示为:{:#x}。".format(11))   # 增加0x
Out[41]: 11转换成十六进制显示为:0xb。
​
In [42]: print("11转换成十六进制显示为:{:#X}。".format(11))   # 增加0X
Out[42]: 11转换成十六进制显示为:0XB。

h, escape {}

If in the process of formatting output, or in the process of ordinary output, when you really want to output {}, you need to use the braces to include the braces { {}} to escape to directly output { }.

In [43]: print("这个{
   
   {}}是要直接输出的,{
   
   {}}里面有内容也可以,就像{
   
   {这个}}一样,而这个{}是要进行格式化输出的。".format('大括号'))
Out[43]: 这个{}是要直接输出的,{}里面有内容也可以,就像{这个}一样,而这个大括号是要进行格式化输出的。

3. Number formatting while setting the format parameter

The above examples are all demonstrated by the format() function in a one-to-one correspondence between placeholders and parameters. If you use position indexes, variable names, dictionaries, lists, etc., can you also format numbers at the same time?

The answer is yes. The ":" identifier in digital format output is used to distinguish position indexes, variable names, etc. from digital formatting symbols. The formatted output methods of the following four examples are equivalent, and the output results are exactly the same.

In [44]: print("使用位置索引,π的值可以显示为:{1:X^12f},100可以显示为:{0:f},或者显示为:{0:&>8,.2f}。".format(100,3.1415926))
Out[44]: 使用位置索引,π的值可以显示为:XX3.141593XX,100可以显示为:100.000000,或者显示为:&&100.00。
​
In [45]: print("使用变量名,π的值可以显示为:{pai:X^12f},100可以显示为:{num:A<f},或者显示为:{num:&>8,.2f}。".format(num=100,pai=3.1415926))
Out[45]: 使用变量名,π的值可以显示为:XX3.141593XX,100可以显示为:100.000000,或者显示为:&&100.00。
​
In [46]: info = {'pai': 3.1415926, 'num': 100}
         print("使用字典,π的值可以显示为:{pai:X^12f},100可以显示为:{num:A<f},或者显示为:{num:&>8,.2f}。".format(**info))
Out[46]: 使用字典,π的值可以显示为:XX3.141593XX,100可以显示为:100.000000,或者显示为:&&100.00。
​
In [47]: info = [3.1415926, 100]
         print("使用列表,π的值可以显示为:{1[0]:X^12f},100可以显示为:{1[1]:A<f},或者显示为:{0:&>8,.2f}。".format(100, info))
Out[47]: 使用列表,π的值可以显示为:XX3.141593XX,100可以显示为:100.000000,或者显示为:&&100.00。

I spent a lot of space above to introduce the formatted output method of the format() function. If everyone can master the content here, not to mention the innocent mastery of the format() function, it is enough to meet the current needs.

Next, I will introduce two other methods of formatting output. Because they are not commonly used, or have been replaced by format(), they will be briefly discussed. If you are interested, you can also learn format as above, for different situations and their Combine to explore one by one. This method is not only the method I use to learn Python, but also the method I suggest you learn to use.

f method

The f method is also a method of formatted output. The format is in the print() function, write an "f" before the string to be printed, which means that there is a placeholder in the following string for formatted output content. Similar to this:

print(f"The content to be printed, the part to be formatted output: {variable name}")

Compared with the flexibility of the format() function, the f method is much simpler. It is somewhat similar to the method of using variables for commands in the format() function. Just use the f method to complete the variable assignment before the print() statement, and write the corresponding variable name in the placeholder in the print() statement.

In [48]: name = 'mnpy'
         gender = '男'
         hobby = 'Python'
         print(f"本文作者:{name},性别:{gender},爱好:{hobby},笔名:{name}。")
Out[48]: 本文作者:mnpy,性别:男,爱好:Python,笔名:mnpy。

The f method can also be used for digital formatted output.

Similar to the format () function for number formatting, it is also distinguished by adding ":" after the variable name in {}. The symbols for number formatting are also common with the format() function and placed after the ":".

In [49]: num=100
         pai=3.1415926
         print(f"使用f方法,π的值可以显示为:{pai:X^12f},100可以显示为:{num:A<f},或者显示为:{num:&>8,.2f}。")
Out[49]: 使用f方法,π的值可以显示为:XX3.141593XX,100可以显示为:100.000000,或者显示为:&&100.00。

% Formatting method

Although we have talked a lot about the formatting output method of the format() function, in fact, the% format specifier method is the originator of the string formatted output, but after Python added the format() function from version 2.6,% The formatting method is gradually being replaced. However, the% formatting method is still in use now, so let's take a brief look.

With the basis of the format() function, the% format symbol method is very easy to understand.

The format() function uses {} as a placeholder and writes number formatting symbols in {}. The% formatting method uses% as a placeholder, and writes number formatting symbols after %.

The format() function writes the parameters in the () after the .format, and the% format symbol method is to write the parameters in the () after the %.

In addition, the formatting symbols are slightly different from the format() function, but with the basis of the format() function, it should be easy for everyone to understand.

 symbol

description

%c

 Formatting characters and their ASCII codes

%s

 Format string

%d

 Format integer

% u

 Format unsigned integer

%O

 Format an unsigned octal number

%x

 Format unsigned hexadecimal number

%X

 Format an unsigned hexadecimal number (uppercase)

%f

 Format floating point numbers, you can specify the precision after the decimal point

%e

 Format floating point numbers in scientific notation

%E

 Same function as %e, format floating point number in scientific notation

%g

 Shorthand for %f and %e

%G

 Shorthand for %F and %E

%p

 Format the address of the variable with a hexadecimal number

m.n

m is the minimum total width of the display, n is the number of digits after the decimal point (if available)

*

Define width or decimal point precision

-

Used for left alignment

+

Show plus sign (+) in front of positive numbers

<sp>

Display a space before positive numbers

#

Display zero ('0') in front of the octal number, display '0x' or '0X' in front of the hexadecimal number (depending on whether you are using'x' or'X')

0

The displayed number is filled with '0' instead of the default space

%

'%%' outputs a single'%'

Here are a few examples of symbols or combinations that are not covered. Please try to explore them.

In [50]: print("如果输出字符串,π的值显示为:%s。" %(3.1415926))
Out[50]: 如果输出字符串,π的值显示为:3.1415926。
​
In [51]: print("如果输出整数,π的值显示为:%d。" %(3.1415926))
Out[51]: 如果输出整数,π的值显示为:3。
​
In [52]: print("如果输出八进制数,11的值显示为:%o;如果输出十六进制数,20的值显示为:%x。" %(8, 20))
Out[52]: 如果输出八进制数,11的值显示为:10;如果输出十六进制数,20的值显示为:14。
​
In [53]: print("如果保留2位小数,π的值显示为:%.2f。" %(3.1415926))
Out[53]: 如果保留2位小数,π的值显示为:3.14。
​
In [54]: print("如果用科学计数法,1000000的值显示为:%.2e。" %(1000000))   # 小数点后保留2位,和format一样,也不写f
Out[54]: 如果用科学计数法,1000000的值显示为:1.00e+06。
​
In [55]: print("左对齐、宽度12、填充空格、默认精度6,π的值显示为:%-12f。"%(3.1415926))
Out[55]: 左对齐、宽度12、填充空格、默认精度6,π的值显示为:3.141593    。
​
In [56]: print("右对齐、宽度12、填充空格、精度2,π的值显示为:%12.2f。"%(3.1415926))   # 不写-就是默认右对齐
Out[56]: 右对齐、宽度12、填充空格、精度2,π的值显示为:3.14。
​
In [57]: print("右对齐、宽度12、填充0、精度2、整数显示+,π的值显示为:%+012.2f。"%(3.1415926))   # 不写-就是默认右对齐
Out[57]: 右对齐、宽度12、填充0、精度2、整数显示+,π的值显示为:+00000003.14。
​
In [58]: print("这个%%是要直接输出的,而这个%s是要进行格式化输出的。" %'百分号')   # %后如果只有一个参数可以不写(),但为了方便阅读,除了本例作为演示没有写(),上面即使只有一个参数,也写()了
Out[58]: 这个%是要直接输出的,而这个百分号是要进行格式化输出的。

The formatted output of strings has been introduced so far. This should be the longest one in all the articles, and it may be a little more difficult. It is recommended that you learn the parameter part of the format() function according to your needs, and then learn the number formatting of the format() function, and come back to understand the f method and the% format symbol method when you use it.

At this point, the string part of Python is basically finished. Have you already felt the power of Python? There are so many operations, methods, functions, and output methods in a single string.

If you learn this, everyone feels a bit boring, please bear with two more articles. In the next two articles, I will introduce you to the related content of numbers and operations. One is that the content of these two parts is very simple, and the other is that after learning these two parts, we are ready to take everyone to the programming link.

At that time, you will not only have boring theoretical knowledge, you can also use what you have learned to write some interesting programs yourself. So, please be sure to stick to it.

 

 


Thanks for reading this article! If you have any questions, please leave a message and discuss together ^_^

Welcome to scan the QR code below, follow the "Yesu Python" public account, read other articles in the "Learning Python with You Hand in Hand" series, or click the link below to go directly.

"Learning Python with You Hand in Hand" 1-Why learn Python?

"Learning Python with you hand in hand" 2-Python installation

"Learning Python with You Hand in Hand" 3-PyCharm installation and configuration

"Learning Python with You Hand in Hand" 4-Hello World!

"Learning Python with You Hand in Hand" 5-Jupyter Notebook

"Learning Python with You Hand in Hand" 6-String Identification

"Learning Python with You Hand in Hand" 7-Index of Strings

"Learning Python with You Hand in Hand" 8-String Slicing

"Learning Python with You Hand in Hand" 9-String Operations

"Learning Python with You Hand in Hand" 10-String Functions

For Fans: Follow the "also said Python" public account, reply "hand 11", you can download the sample sentences used in this article for free.

Also talk about Python-a learning and sharing area for Python lovers

 

Guess you like

Origin blog.csdn.net/mnpy2019/article/details/98761643