【问题标题】:How do I format a string value as an actual string如何将字符串值格式化为实际字符串
【发布时间】:2014-04-20 23:05:31
【问题描述】:

考虑一下这个字典:

d = {
   value_1 = 'hello',
   value_2 = False,
   value_3 = 29
}

我想将这些变量写在这样的文件中:

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

【问题讨论】:

    标签: python string dictionary


    【解决方案1】:

    应使用值的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
    

    【讨论】:

      【解决方案2】:

      使用repr**dict(…) 也很傻。

      "{key} = {value}".format(key=k, value=repr(v))
      

      【讨论】:

        猜你喜欢
        • 2017-11-09
        • 1970-01-01
        • 1970-01-01
        • 2022-07-05
        • 2017-07-14
        • 2015-03-26
        • 1970-01-01
        • 2010-10-16
        • 1970-01-01
        相关资源
        最近更新 更多