字符串格式化表达式

您所在的位置:网站首页 python中的类型码 字符串格式化表达式

字符串格式化表达式

2023-03-28 17:16| 来源: 网络整理| 查看: 265

对于更高级的特定类型的格式化,可在格式化表达式中使用表7-4中列出的任何转换类型码;它们出现在替换目标的%字符后。C程序员将会认识大多数这些转换类型码,因为Python字符串格式化支持所有常见的C printf 格式化码(但返回结果,而非像 printf 那样显示它)。表中的一些格式码提供了格式化同种类型的可选方式;比如,%e, %f 和 %g 都提供了格式化浮点数字的可选方式。

image-20230228103605611

事实上,表达式左边的格式化字符串中的转换目标使用它们自己的相对复杂语法,支持许多转换操作。转换目标的通常结构看起来像这样:

%[(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就将被对应值的默认打印字符串所代替(不管类型)。

本文章首发在 LearnKu.com 网站上。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3