【问题标题】:Format syntax in PythonPython中的格式化语法
【发布时间】:2012-09-06 13:19:14
【问题描述】:

有没有办法更好地编写这行代码:

"""{a};{b};{c};{d}""".format(a = myDictionary[a], b = myDictionary[b], c = myDictionary[c], d = myDictionary[d])

类似的东西?

"""{a};{b};{c};{d}""".format(myDictionary)

【问题讨论】:

    标签: python syntax format


    【解决方案1】:

    在字典上使用keyword expansion

    "{a};{b};{c};{d}".format(**myDictionary)
    

    【讨论】:

    • 正是我想要的。谢谢:-)
    【解决方案2】:

    format 可以取消引用它的参数:

    >>> D=dict(a=1,b=2,c=3,d=4)
    >>> '{0[a]};{0[b]};{0[c]};{0[d]}'.format(D)
    '1;2;3;4'
    

    类可以使用类似的语法:

    >>> class C:
    ...  a=1
    ...  b=2
    ...  c=3
    ...  d=4
    ...
    >>> '{0.a};{0.b};{0.c};{0.d}'.format(C)
    '1;2;3;4'
    

    请参阅Format Specification Mini-Language

    【讨论】:

      【解决方案3】:
      """%(a)s;%(b)s;%(c)s;%(d)s""" % myDictionary
      

      尽管有很多争议和推动,传统的字符串格式化操作符“%”并没有离开的动机(也没有迹象),因为有了它,很多事情变得更简单了。

      【讨论】:

        【解决方案4】:

        这是你要找的吗?

        di = {
          'key1': 'value1',
          'key2': 'value2',
          'key3': 'value3'
        }
        
        print "value of key3 is: %(key3)s" % di
        

        key3的值为:value3

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-08-16
          • 2019-06-12
          • 2023-02-16
          • 1970-01-01
          • 2022-01-12
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多