Reputation: 554
>>> d = {}
>>> s = str(d)
>>> print s
{}
I need an empty string instead.
Upvotes: 5
Views: 2560
Reputation: 981
I would like to propose sub classing dict and overriding the __str__
method:
class DontForgetToDoYourTaxes(dict):
def __str__(self):
return self or ""
Then to use:
d = DontForgetToDoYourTaxes()
print d # ""
d["ayy"] = "lmao"
print d # "{'ayy': 'lmao'}"
Upvotes: 0
Reputation: 20435
Convert each item in the dictionary to a string, then join them with the empty string,
>>> ''.join(map(str,d))
Upvotes: 0
Reputation: 17612
Take a look at the docs:
Truth Value Testing
Any object can be tested for truth value, for use in an
if
orwhile
condition or as operand of the Boolean operations below. The following values are considered false:
None
False
- zero of any numeric type, for example,
0
,0.0
,0j
.- any empty sequence, for example,
''
,()
,[]
.- any empty mapping, for example,
{}
.- instances of user-defined classes, if the class defines a
__bool__()
or__len__()
method, when that method returns the integer zero orbool
valueFalse
.
So your empty dictionary turns out to be False
according to that bolded rule. So you can use:
d = {}
if not d:
s = ''
else:
s = str(d)
Upvotes: 2
Reputation: 48536
You can do it with the shortest way as below, since the empty dictionary is False
, and do it through Boolean Operators.
>>> d = {}
>>> str(d or '')
''
Or without str
>>> d = {}
>>> d or ''
''
If d
is not an empty dictionary, convert it to string with str()
>>> d['f'] = 12
>>> str(d or '')
"{'f': 12}"
Upvotes: 16
Reputation: 22312
An empty dict object is False
when you try to convert it to a bool object. But if there's something in it, it would be True
. Like empty list, empty string, empty set, and other objects:
>>> d = {}
>>> d
{}
>>> bool(d)
False
>>> d['foo'] = 'bar'
>>> bool(d)
True
So it's simple:
>>> s = str(d) if d else ''
>>> s
"{'foo': 'bar'}"
>>> d = {}
>>> s = str(d) if d else ''
>>> s
''
Or just if not d: s = ''
if you don't need s
be string of the dict when there's something in the dict.
Upvotes: 8