【问题标题】:Why is the order of output as is - I would think it has to be otherwise? [closed]为什么输出顺序是原样 - 我认为它必须是其他的? [关闭]
【发布时间】:2019-05-19 13:45:21
【问题描述】:
>>> 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

【问题讨论】:

  • 我不知道输出是怎样的 bill,sean and john ,我很困惑应该是 bill,john and sean 还是 john,sean and bill
  • 为什么你认为输出应该2, 1, 01, 2, 0,而不是0, 1, 2

标签: python python-3.x printing format


【解决方案1】:

你正在做的格式是位置

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    相关资源
    最近更新 更多