[英]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: 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'
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
key3的值是:value3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.