Python format formatting function

Python 字符串Python String


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

>>>"{} {}".format("hello", "world") # Without setting a specified position, uses the default order 'hello world' >>> "{0} {1}".format("hello", "world") # Set the specified position 'hello world' >>> "{1} {0} {1}".format("hello", "world") # Set the specified position 'world hello world'

You can also set parameters:

Example

#!/usr/bin/python # -*- coding: UTF-8 -*- print("Website name: {name}, Address {url}".format(name="Example", url="www.example.com")) # Set parameters via dictionary site = {"name": "Example", "url": "www.example.com"} print("Website name: {name}, Address {url}".format(**site)) # Set parameters via list index my_list = ['Example', 'www.example.com'] print("Website name: {0".format(my_list)) # "0" is required

The output result is:

网站名:Example, 地址 www.example.com
网站名:Example, 地址 www.example.com
网站名:Example, 地址 www.example.com

You can also passstr.format()an object:

Example

#!/usr/bin/python # -*- coding: UTF-8 -*- class AssignValue(object): def __init__(self, value): self.value = value my_value = AssignValue(6) print('value is: {0.value}'.format(my_value)) # "0" is optional

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
NumberFormatOutputDescription
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

#!/usr/bin/python # -*- coding: UTF-8 -*- print ("The position corresponding to {} is {{0}}".format("example"))

The output result is:

example 对应的位置是 {0}

Python 字符串Python String

Other extensions