首先吐槽一下python的help()html
help(format)
结果是python
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.“ 找软件翻译了一下,大概意思是说: “执行字符串格式化操做。调用此方法的字符串能够包含文本或更换由大括号{}分隔的字段。每一个替换字段包含数字位置参数的索引,或关键字参数的名称。返回一个字符串,其中每一个替换字段将被替换为相应参数的字符串值”this
这里给出的说明比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'
以上是根据官方文档得出的一些理解,不足的地方,还请高人指点。code
参考资料:https://docs.python.org/2.7/library/stdtypes.html?highlight=format#str.formatorm