Python: how to get rid of spaces in str(dict)?
<p>For example, if you use str() on a dict, you get:</p>

<pre><code>&gt;&gt;&gt; str({'a': 1, 'b': 'as df'})
"{'a': 1, 'b': 'as df'}"
</code></pre>

<p>However, I want the string to be like:</p>

<pre><code>"{'a':1,'b':'as df'}"
</code></pre>

<p>How can I accomplish this?</p>

<p>You could build the compact string representation yourself:</p>

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

<p>It will leave extra spaces inside string representations of nested <code>list</code>s, <code>dict</code>s etc.</p>

<p>A much better idea is to use the <a href="https://docs.python.org/3/library/json.html#json.dumps" rel="nofollow"><code>json.dumps</code></a> function with appropriate separators:</p>

<pre><code>In [15]: import json

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

<p>This will work correctly regardless of the inner structure of <code>dct</code>.</p>

python