Home  >  Article  >  Backend Development  >  What does python’s format function mean?

What does python’s format function mean?

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-06-21 09:25:3110941browse

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.

What does python’s format function mean?

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

What does python’s format function mean?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn