>>> 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 Sean
或John, Sean and Bill
。
答案 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
执行字符串格式化操作。调用此方法的字符串可以包含文字文本或用大括号{}分隔的替换字段。每个替换字段包含位置参数的数字索引或关键字参数的名称。
也可以使用名称代替位置:
names = "{S}, {B} and {J}".format( J = 'John', B = 'Bill', S = 'Sean')
print(names)
打印
Sean, Bill and John