Home  >  Article  >  Backend Development  >  String formatting: How to use % and .format

String formatting: How to use % and .format

anonymity
anonymityOriginal
2019-05-27 10:46:205924browse

There are two formatting methods for strings, namely placeholder (%) and format.

String formatting: How to use % 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.

String formatting: How to use % and .format

%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]: &#39;2016-12-31:计算机PYTHON的CPU 占用率为10%。&#39;

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]: &#39;圆周率是3.1415926...&#39;
"圆周率{{{1}{2}}}是{0}".format("无理数",3.1415926,"...")
Out[12]: &#39;圆周率{3.1415926...}是无理数&#39;
s="圆周率{{{1}{2}}}是{0}" #大括号本身是字符串的一部分
sOut[14]: &#39;圆周率{{{1}{2}}}是{0}&#39;
s.format("无理数",3.1415926,"...") #当调用format()时解析大括号
Out[15]: &#39;圆周率{3.1415926...}是无理数&#39;

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!

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