建议使用format()方法
字符串操作 对于 %
, 官方以及给出这种格式化操作已经过时,在 Python
的未来版本中可能会消失。 在新代码中使用新的字符串格式。因此推荐大家使用format()
来替换 %.
format 方法系统复杂变量替换和格式化的能力,因此接下来看看都有哪些用法。
format()
这个方法是来自 string
模块的Formatter
类里面的一个方法,属于一个内置方法。因此可以在属于 string 对象的范畴都可以调用这个方法。
语法结构
这个方法太强大了,官方的用户是。
replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name ::= arg_name ("." attribute_name | "[" element_index "]")*
arg_name ::= [identifier | integer]
attribute_name ::= identifier
element_index ::= integer | index_string
index_string ::= <any source character except "]"> +
conversion ::= "r" | "s" | "a"
format_spec ::= <described in the next section>
针对 format_spec 的用法如下
format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]
fill ::= <a character other than '}'>
align ::= "<" | ">" | "=" | "^"
sign ::= "+" | "-" | " "
width ::= integer
precision ::= integer
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
说明:
<
强制字段在可用空间内左对齐>
强制字段在可用空间内右对齐=
填充位于符号(如果有的话)之后,但位于数字之前^
强制场位于可用空间的中心
常用的方法有下面几个,format()方法中的槽除了包括参数序号,还可以包括格式控制信息