user2298943
user2298943

Reputation: 632

How do I format a string value as an actual string

Consider this dict:

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

I want to write these vars in a file like this:

value_1 = 'hello'
value_2 = False
value_3 = 29

I've tried:

f.write(
    "\n".join(
        [
            "{key} = {value}".format(**dict(key=k, value=v))
            for k, v in d.items()
        ]
    )
)

But the output is

value_1 = hello  # not a string
value_2 = False
value_3 = 29

Upvotes: 2

Views: 66

Answers (2)

user1804599
user1804599

Reputation:

Use repr. Also **dict(…) is silly.

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

Upvotes: 2

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251136

Use should use the repr representation of the values. Use {!r} in string formatting for that:

>>> x = 'hello'
>>> print x
hello
>>> print repr(x)
'hello'
>>> print '{!r}'.format(x)
'hello'

Demo:

>>> 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

Upvotes: 5

Related Questions