Python3 中的str.format方法

版权声明:未经博主允许,请勿转载原创,谢谢! https://blog.csdn.net/mystonelxj/article/details/89844798

在python中使用help命令窗口该方法获得如下结果

>>> help(str.format)
Help on method_descriptor:

format(...)
    S.format(*args, **kwargs) -> str
    
    Return a formatted version of S, using substitutions from args and kwargs.
    The substitutions are identified by braces ('{' and '}').

根据上述的方法解释,是指该方法是用来返回字符串的格式化后结果,在该方法中在参数args与kwargs使用了替代物,替代物需要用大括号'{}'标识。

按照上述说法,该方法有两个参数,可是查找了半天,也没有见到有两个参数的使用。后来在帮助文档中发现如下方法说明

str.format(*args, **kwargs)
Perform a string formatting operation. The string on which this method is called can 
contain literal text or replacement fields delimited by braces {}. Each replacement field
 contains either the numeric index of a positional argument, or the name of a keyword argument.
 Returns a copy of the string where each replacement field is replaced with the
 string value of the corresponding argument.


>>> "The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'

根据这个说法,才发现原来这里的两个参数并不是指的共用的方式,而是一种替换选择的模式,换言之,可以使用args变量,也可以使用kwargs变量,如果两个都使用,则按照未定义关键字的在前,定义关键字的在后形式展示

如下所示

>>> x='this is my x test'
>>> m='ok,{}, m, {x}'
>>> m.format(1+2,x=x)
'ok,3, m, this is my x test'

即使在定义时空括号在后,在format时也需要提前处理

>>> x='this is my x test'
>>> m='ok, {x},{},ok'
>>> m.format(1+2,x=x)
'ok, this is my x test,3,ok'

在format时候可以传递多个参数,但是不能少于字符串规定的未定义关键字的数量,也不能少于定义关键字的数量,否则就报错

>>> x='this is my x test'
>>> y='this is my y test'
>>> m='ok, {x},{},ok'
>>> m.format(1+2,2+3,x=x,y=y)
'ok, this is my x test,3,ok'

 

猜你喜欢

转载自blog.csdn.net/mystonelxj/article/details/89844798