Python String Formatting Method Documentation

The content of the string part is the value of the specified variable

1. f"str"

Example:

a = 3.1415
print(f"result: {
      
      a:+0>7.2f}")
>>>
result: +003.14

Explanation:
  Except for the variable name, the rest can be omitted

f"result: {
      
      [a 变量名]:[+ 显示正数符号][0 补位字符][> 对齐方式][7 宽度][.2 保留小数位数][f 数据类型]}"
alignment < align left
> right align
^ center alignment
= Signs are left-aligned, values ​​are right-aligned
type of data c The Unicode character corresponding to the integer
s string
d integer
f floating point
% percentage
o Octal
x/X hexadecimal
and and Index representation
g/G 6 significant figures are reserved, and the integer part >= 7 is represented by an exponent

Supplement:
(1) Thousand separator

a = 123456789
print(f"result: {
      
      a:*^20,.2f}")
print(f"result: {
      
      a:*^20_.2f}")
>>>
result: ***123,456,789.00***
result: ***123_456_789.00***

2. “str”.format()

Example:

a = 3.14
print("result: {0:x>10.2%}, {0}".format(a))
>>>
result: xxx314.00%, 3.14

Explanation:
  The usage of the format part is consistent with the first method. When each {}corresponds to a variable, the index can be ignored, for example “{}{}”.format(a, b).

"result: {[0 变量索引][:x>10.2% 格式]}".format(a)

3. “str”%()

Example:

a = 3.14
b = 2.33
print("result: %06.2f, %+6.2f" % (a, b))
>>>
result: 003.14,  +2.33

explain:

"%[0 格式符][6 宽度][.2 保留小数位数][f 数据类型]"
format character - align left
0 Right justify and pad with 0
+ Right-aligned and + is displayed in front of positive numbers
space Right-aligned with spaces before positive numbers (for alignment with negative numbers)

Supplement:
(1) To keep the number of decimal places
  , use *and the following parameters to set the number of decimal places

a = 3.14
b = 2.33
print("result: %.*f, %+6.*f" % (2, a, 3, b))
>>>
result: 3.14, +2.330

Guess you like

Origin blog.csdn.net/weixin_43605641/article/details/127964759