Starting from Python 2.6, a new function str.format() for formatting strings has been added, which enhances the function of string formatting.
The basic syntax is to use {} and : to replace the previous %.
The format function can accept unlimited parameters, and the positions do not need to be in order.
format format function
Example
>>>"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序 'hello world' >>> "{0} {1}".format("hello", "world") # 设置指定位置 'hello world' >>> "{1} {0} {1}".format("hello", "world") # 设置指定位置 'world hello world'
You can also set parameters:
Related recommendations: "Python Video Tutorial"
Example
#!/usr/bin/python # -*- coding: UTF-8 -*- print("网站名:{name}, 地址 {url}".format(name="php中文网", url="www.php.cn")) # 通过字典设置参数 site = {"name": "php中文网", "url": "www.php.cn"} print("网站名:{name}, 地址 {url}".format(**site)) # 通过列表索引设置参数 my_list = ['php中文网', 'www.php.cn'] print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的
The output result is:
网站名:php中文网, 地址 www.php.cn 网站名:php中文网, 地址 www.php.cn 网站名:php中文网, 地址 www.php.cn
You can also pass in objects to str.format() :
Example
#!/usr/bin/python# -*- coding: UTF-8 -*- class AssignValue(object): def __init__(self, value): self.value = value my_value = AssignValue(6) print('value 为: {0.value}'.format(my_value)) # "0" 是可选的
The output result is:
value 为: 6
Number formatting
The following table shows str.format() Various ways to format numbers:
>>> print("{:.2f}".format(3.1415926)); 3.14
In addition, we can use braces {} to escape braces, as shown in the following example:
Example
#!/usr/bin/python # -*- coding: UTF-8 -*- print ("{} 对应的位置是 {{0}}".format("php"))
The output result is:
php and the corresponding position is {0}
The above is the detailed content of What does python's format function mean?. For more information, please follow other related articles on the PHP Chinese website!