Python format formatting function
Starting with Python 2.6, a new function for formatting strings was addedstr.format(), which enhances the functionality of string formatting.
The basic syntax is to use{}and:to replace the previous% 。
The format function can accept an unlimited number of arguments, and their positions do not need to be in order.
Example
You can also set parameters:
Example
The output result is:
网站名:Example, 地址 www.example.com 网站名:Example, 地址 www.example.com 网站名:Example, 地址 www.example.com
You can also passstr.format()an object:
Example
The output result is:
value 为: 6
Number formatting
The following table shows various methods for formatting numbers with str.format():
>>> print("{:.2f}".format(3.1415926))
3.14
| Number | Format | Output | Description |
|---|---|---|---|
| 3.1415926 | {:.2f} | 3.14 | Keep two decimal places |
| 3.1415926 | {:+.2f} | +3.14 | Keep two decimal places with sign |
| -1 | {:-.2f} | -1.00 | Keep two decimal places with sign |
| 2.71828 | {:.0f} | 3 | No decimals |
| 5 | {:0>2d} | 05 | Zero-pad the number (fill on the left, width 2) |
| 5 | {:x<4d} | 5xxx | Pad the number with x (fill on the right, width 4) |
| 10 | {:x<4d} | 10xx | Pad the number with x (fill on the right, width 4) |
| 1000000 | {:,} | 1,000,000 | Number format with comma separators |
| 0.25 | {:.2%} | 25.00% | Percentage format |
| 1000000000 | {:.2e} | 1.00e+09 | Exponential notation |
| 13 | {:>10d} | 13 | Right-aligned (default, width 10) |
| 13 | {:<10d} | 13 | Left-aligned (width 10) |
| 13 | {:^10d} | 13 | Center-aligned (width 10) |
| 11 | '{:b}'.format(11)
'{:d}'.format(11)
'{:o}'.format(11)
'{:x}'.format(11)
'{:#x}'.format(11)
'{:#X}'.format(11) |
1011 11 13 b 0xb 0XB |
Base |
^, <, >They are center, left, and right alignment respectively, followed by width,:After the sign comes the fill character, which can only be one character. If not specified, spaces are used by default.
+means to display before positive numbers+, and before negative numbers-; (space) means add a space before positive numbers
b, d, o, x are binary, decimal, octal, and hexadecimal respectively.
In addition, we can use curly braces{}to escape curly braces, as in the following example:
Example
The output result is:
example 对应的位置是 {0}
Other extensions
Python String