【问题标题】:Python: different types of field name in string formatting [duplicate]Python:字符串格式中不同类型的字段名称[重复]
【发布时间】:2018-02-14 18:51:33
【问题描述】:

考虑以下字典:

dic1 = {1:'string', '1': 'int'}

让我们应用字符串格式:

print("the value is {0[1]}".format(dic1))
result --> the value is string

但是我怎样才能得到 'the value is int' 结果呢?

【问题讨论】:

    标签: python dictionary string-formatting field-names


    【解决方案1】:

    应该就是这个。

    print("the value is {0}".format(dic1['1']))
    

    {0} 仅充当要放入字符串的文本的占位符。所以一个例子是。

    >>> x=1
    >>> y=2
    >>> z=[3,4,5]
    >>> print "X={0} Y={1} The last element in Z={2}".format(x,y,z[-1])
    X=1 Y=2 The last element in Z=5
    

    您也可以这样做来改变现状。数字引用了格式命令中要使用的参数。

    >>> print "X={0} Y={1} The last element in Z={0}".format(x,y,z[-1])
    X=1 Y=2 The last element in Z=1
    

    现在看到我将字符串更改为Z={0},它实际上是在.format(x,y,z[-1]) 命令中使用x

    【讨论】:

    • 谢谢。工作!但我认为例如有一个参数并在多个占位符中使用它会更容易。例如,类似于您的示例:我会在格式函数中调用 z 一次并在多个占位符中使用,例如:“Z1={0[0]}, Z2={0[1]}”.format(z)
    【解决方案2】:

    有效,

    print("the value is {0}".format(dic1['1']))
    

    编辑以回答@Afshin 的评论

    您可以在可迭代对象之前使用 * 运算符在函数调用中扩展它。例如,

    a = [1, 2, 3]
    print("X={0} Y={1} The last element in Z={2}".format(*a))
    

    d = {'x': 1, 'y': 2, 'z': 3}
    print("X={x} Y={y} The last element in Z={z}".format(**d))
    

    【讨论】:

    • 谢谢。请查看我对@Zack 回答的评论。
    猜你喜欢
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    • 2017-09-28
    • 1970-01-01
    • 2015-01-07
    相关资源
    最近更新 更多