为什么输出顺序保持原样-我认为必须是其他顺序?

时间:2019-05-19 13:45:22

标签: python python-3.x printing format

>>> names = "{1}, {2} and {0}".format('John', 'Bill', 'Sean')
>>> print(names)
Bill, Sean and John
>>> print(type(names))
<class 'str'>

我不明白为什么输出是Bill, Sean and John

我很困惑,认为应该是Bill, John and SeanJohn, Sean and Bill

1 个答案:

答案 0 :(得分:2)

您正在使用的格式是位置

names = "{1}, {2} and {0}".format('John', 'Bill', 'Sean')
#         1.   2.      0.     <=>    0.     1.      2.

'John'位于位置0,'Bill'位于位置1,'Sean'位于位置2,作为给.format('John', 'Bill', 'Sean')的参数。

因此打印:

Bill, Sean and John

请参阅:str.format documentation

  

执行字符串格式化操作。调用此方法的字符串可以包含文字文本或用大括号{}分隔的替换字段。每个替换字段包含位置参数的数字索引或关键字参数的名称。

也可以使用名称代替位置:

names = "{S}, {B} and {J}".format( J = 'John', B = 'Bill', S = 'Sean')

print(names) 

打印

Sean, Bill and John