Starting from Python2.6, a new string formatting function str.format() 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 an unlimited number of parameters, and the positions can be out of order.
E.g
"{} {}". format("hello","world") #Do not set the specified location, follow the default order
' hello world'"{0} {1}".format("hello","world") #Set the specified location
' hello world'"{1} {0} {1}".format("hello","world") #Set the specified location
' world hello world'
Parameters can also be set
#! /usr/bin/python
# - *- coding: UTF-8-*-print("Site name:{name},address{url}".format(name="python learning network", url="www.py.cn"))
# Set parameters via dictionary
site ={"name":"python learning network","url":"www.py.cn"}print("Site name:{name},address{url}".format(**site))
# Set parameters by list index
my_list =['ZaLou.Cn','www.zalou.cn']print("Site name:{0[0]},address{0[1]}".format(my_list)) # "0"It's required
Output result
Website name: ZaLou.Cn, address www.zalou.cn
Website name: ZaLou.Cn, address www.zalou.cn
Website name: ZaLou.Cn, address www.zalou.cn
So far, this article on how to use the format function in python is introduced. For more related python format function usage content, please search for ZaLou.Cn's previous articles or continue to browse related articles below. Hope you will support ZaLou more in the future. Cn!
Recommended Posts