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

String formatting: How to use % and .format

anonymity
Release: 2019-05-27 10:46:20
Original
6000 people have browsed it

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
Copy after login

%sExample (Python3.0) :

name = "makes"
print("my name is %s" %name)
#my name is makes
Copy after login

%f Example (Python3.0):

print("%6.3f" % 2.3)
#2.300
print("%f" %2.3)
#2.300000
Copy after login

format() method, the basic format is:

     <模板字符串>.format(<逗号分隔的参数>)
Copy after login

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;
Copy after login

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;
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template