字符串格式化表达式——高级格式化表达式语法 | 第二部分 类型与操作 —— 第 7 章: 字符串基础 |《学习 python:强大的面向对象编程(第 5 版)》| python 技术论坛-大发黄金版app下载
对于更高级的特定类型的格式化,可在格式化表达式中使用表7-4中列出的任何转换类型码;它们出现在替换目标的%字符后。c程序员将会认识大多数这些转换类型码,因为python字符串格式化支持所有常见的c printf
格式化码(但返回结果,而非像 printf
那样显示它)。表中的一些格式码提供了格式化同种类型的可选方式;比如,%e
, %f
和 %g
都提供了格式化浮点数字的可选方式。
事实上,表达式左边的格式化字符串中的转换目标使用它们自己的相对复杂语法,支持许多转换操作。转换目标的通常结构看起来像这样:
%[(keyname)][flags][width][.precision]typecode
表7-4的第一列中的类型码字符出现在这个目标字符串格式的末尾。在 %
和类型码字符之间,可以做下面这些事:
-
提供一个键名来索引表达式右边使用的字典。
# a dictionary with information about a person person = { "name": "alice", "age": 25, "occupation": "engineer" } # using string formatting to display information about the person message = "my name is %(name)s, i am %(age)d years old, and i work as a %(occupation)s." print(message % person)
-
列出标记,它们指定像左对齐(-),数字符号( ),在整数前的空白和负数前的
-
,还有0填充(0)。# a dictionary with information about a product product = { "name": "widget", "price": 29.99, "quantity": 3 } # using string formatting with flags to display information about the product message = "product: %(name)s, price: %(price) .2f, quantity: %(quantity)03d" print(message % product)
-
为被替代文本给出总的最小字段宽度。
# a dictionary with information about a book book = { "title": "the catcher in the rye", "author": "j.d. salinger", "year": 1951, "pages": 224 } # using string formatting with width to display information about the book message = "title: %(title)s, author: %(author)s, year: %(year)d, pages: %(pages)4d" print(message % book)
-
设置数位(精确度)在浮点数的小数点后显示。
# a dictionary with information about a circle circle = { "radius": 3.14159, } # using string formatting with precision to display information about the circle message = "the area of the circle is %(area).2f square units" circle["area"] = 3.14159 * circle["radius"] ** 2 print(message % circle)
宽度和精确度部分都可以*被编码为 ``** 来指定它们应该从表达式右边的多个输入值的下一项来获取它们的值(当这些值在运行时才知道时会很有用)。
如果不需要任何这些额外的工具,在格式化字符串中一个简单的%s
就将被对应值的默认打印字符串所代替(不管类型)。