首先吐槽一下python的help()
help(format)
结果是
format(...) format(value[, format_spec]) -> string Returns value.__format__(format_spec) format_spec defaults to ""
给出的内容十分简洁,可也没看明白。然后去docs.python.org去找。内容如下: ”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.“ 找软件翻译了一下,大概意思是说: “执行字符串格式化操作。调用此方法的字符串可以包含文本或更换由大括号{}分隔的字段。每个替换字段包含数字位置参数的索引,或关键字参数的名称。返回一个字符串,其中每个替换字段将被替换为相应参数的字符串值”
这里给出的说明比help()的说明强多了,但没办法,智商是硬伤,还得放到代码中慢慢理解。 上代码:
#先创建个变量a,并给他赋个值a='a={},b={}'#再使用format方法a.format(1,2)#此处输出的结果是'a=1,b=2'#这里大概就是“调用此方法的字符串可以包含文本或更换由大括号{}分隔的字段”这段的意思#我们再修改一下变量a的内容a='a={0},b={1}'a.format(1,2)#此处输出的结果是'a=1,b=2'#结果没什么变化,那么我们将0和1换个位置试试看a='a={1},b={0}'a.format(1,2)#此处输出的结果是'a=2,b=1'#这里就应了“每个替换字段包含数字位置参数的索引,返回一个字符串,其中每个替换字段将被替换为相应参数的字符串值”这段话。#而”或关键字参数的名称"要怎么理解呢?我们接着往下看a='b={b},c={c}'a.format(b='1',c='2')#此处输出的结果是'b=1,c=2'#我们把format(b='1',c='2')中b,c的位置换一下a.format(c='2',b='1')#此处输出的结果是'b=1,c=2'
以上是根据官方文档得出的一些理解,不足的地方,还请高人指点。
参考资料: