There are two formatting methods for strings, namely placeholder (%) and format.
The placeholder method is widely used in Python2.x. As Python3.x becomes more and more widely used, the format method is more widely used.
%dExample (Python3.0):
age = 29 print("my age is %d" %age) #my age is 29
%sExample (Python3.0) :
name = "makes" print("my name is %s" %name) #my name is makes
%f Example (Python3.0):
print("%6.3f" % 2.3) #2.300 print("%f" %2.3) #2.300000
format() method, the basic format is:
<模板字符串>.format(<逗号分隔的参数>)
After calling the format() method, a new string will be returned, and the parameters will be numbered starting from 0.
"{}:计算机{}的CPU 占用率为{}%。".format("2016-12-31","PYTHON",10) Out[10]: '2016-12-31:计算机PYTHON的CPU 占用率为10%。'
The format() method can very conveniently connect different types of variables or content. If you need to output curly brackets, use {{ to represent {, }} to represent }, for example:
"{}{}{}".format("圆周率是",3.1415926,"...") Out[11]: '圆周率是3.1415926...' "圆周率{{{1}{2}}}是{0}".format("无理数",3.1415926,"...") Out[12]: '圆周率{3.1415926...}是无理数' s="圆周率{{{1}{2}}}是{0}" #大括号本身是字符串的一部分 sOut[14]: '圆周率{{{1}{2}}}是{0}' s.format("无理数",3.1415926,"...") #当调用format()时解析大括号 Out[15]: '圆周率{3.1415926...}是无理数'
The above is the detailed content of String formatting: How to use % and .format. For more information, please follow other related articles on the PHP Chinese website!