Python库源代码详解之string库(续2) format函数

2026-04-01 10:24:58

1、导入string库文件,输入命令:gedit /usr/lib/python2.7/string.py,如图所示:第537--656行,主要包含:format,vformat,_vformat等函数.调用关系format->vformat->_vformat,我们从底层一步步分析代码如何实现.

Python库源代码详解之string库(续2) format函数

2、首先看函数_vformat(self, format_string, args, kwargs, used_args, recursion_depth):

1:568行判断递归深度参数,小于0抛出异常;

2:570行定义列表.存放format_string分割的参数元素.

3:572行调用parse函数返回迭代器;

4:575-576行给result列表增加元素,该元素是从format_string分割的literal_text参数.

5:579行:因为参数field_name可能是None,所以进行判断;

6:585-586行:调用get_field函数从field_name返回该对象的引用以及使用过的参数,并把该参数增加到set集合内.

7:589-592行:对第6步对像进行转换并递归调用_vformat.

8:596-598行:分离的参数join成字符串.

Python库源代码详解之string库(续2) format函数

3、vformat函数增加了used_args的集合还有嵌套次数参数,传给函数_vformat;而最外层的format函数是对参数进行检查以及返回正确的fromat_string参数.

Python库源代码详解之string库(续2) format函数

4、format函数完整的语法如图所示:

整体由三部分组成:field_name,conversion,format_spec;

field_name:参数的索引位置或keyword

conversion:形式有3种,如果是!s,效果等同str(string_arg);

                     如果是!r,效果等同repr(string_arg);

                     如果是!a,效果等同ascii(string_arg)

format_spec参数见后文分析.

Python库源代码详解之string库(续2) format函数

5、format_spec参数由6类可选参数构成,如图所示:

fill:对齐情况下的填充字符'}'除外;

align:对齐方式;

sign:符号选择,只对数据类型生效;

width,precision:格式宽度和精度;

type:整数以及浮点数的类型.

Python库源代码详解之string库(续2) format函数

6、下文举例说明format如何使用conversion域

Python库源代码详解之string库(续2) format函数

7、下文举例说明format如何使用field_name域,可以看到本版本并不支持参数!a,和文档有出入.

Python库源代码详解之string库(续2) format函数

8、下文举例说明format_spec参数如何使用参数fill和align

Python库源代码详解之string库(续2) format函数

9、最后说明下如果用format_spec的sign,width,precision和type参数,如图所示:

Python库源代码详解之string库(续2) format函数

猜你喜欢