dspjm dspjm - 1 year ago 92
Python Question

Python: how to get rid of spaces in str(dict)?

For example, if you use str() on a dict, you get:

>>> str({'a': 1, 'b': 'as df'})
"{'a': 1, 'b': 'as df'}"

However, I want the string to be like:

"{'a':1,'b':'as df'}"

How can I accomplish this?

Answer Source

You could build the compact string representation yourself:

In [9]: '{' + ','.join('{0!r}:{1!r}'.format(*x) for x in dct.items()) + '}'
Out[9]: "{'b':'as df','a':1}"

It will leave extra spaces inside string representations of nested lists, dicts etc.

A much better idea is to use the json.dumps function with appropriate separators:

In [15]: import json

In [16]: json.dumps(dct, separators=(',', ':'))
Out[16]: '{"b":"as df","a":1}'

This will work correctly regardless of the inner structure of dct.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download