考虑一下这个命令:
d = {
value_1 = 'hello',
value_2 = False,
value_3 = 29
}
我想将这些var写入这样的文件中:
value_1 = 'hello'
value_2 = False
value_3 = 29
我试过了:
f.write(
"\n".join(
[
"{key} = {value}".format(**dict(key=k, value=v))
for k, v in d.items()
]
)
)
但是输出是
value_1 = hello # not a string
value_2 = False
value_3 = 29
使用应使用repr
值的表示形式。用于{!r}
字符串格式:
>>> x = 'hello'
>>> print x
hello
>>> print repr(x)
'hello'
>>> print '{!r}'.format(x)
'hello'
演示:
>>> from StringIO import StringIO
>>> c = StringIO()
>>> d = {
... 'value_1' : 'hello',
... 'value_2' : False,
... 'value_3' : 29
... }
>>> for k, v in d.items():
... c.write("{} = {!r}\n".format(k, v))
...
>>> c.seek(0)
>>> print c.read()
value_1 = 'hello'
value_3 = 29
value_2 = False
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句