简体   繁体   中英

Format syntax in Python

Is there a way to write this line of code in a better way :

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

something like this ?

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

在字典上使用关键字扩展

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

format can dereference its parameters:

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

A similar syntax can be used on classes:

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

See the Format Specification Mini-Language .

"""%(a)s;%(b)s;%(c)s;%(d)s""" % myDictionary

尽管存在很多争议和推动,传统的字符串格式化操作符“%”没有动机(也没有迹象)可以消失,因为很多事情都比较简单。

Is this what you looking for?

di = {
  'key1': 'value1',
  'key2': 'value2',
  'key3': 'value3'
}

print "value of key3 is: %(key3)s" % di

value of key3 is: value3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM