>>> d = {}
>>> s = str(d)
>>> print s
{}
我需要一个空字符串代替。
>>> d = {}
>>> s = str(d)
>>> print s
{}
False
,并且使用布尔运算符实现。>>> d = {}
>>> str(d or '')
''
或者不使用 str
>>> d = {}
>>> d or ''
''
如果d
不是一个空字典,则使用str()
将其转换为字符串。
>>> d['f'] = 12
>>> str(d or '')
"{'f': 12}"
当你尝试将空字典转换为布尔对象时,它是False
。但如果其中有内容,则为True
。就像空列表、空字符串、空集合和其他对象一样:
>>> d = {}
>>> d
{}
>>> bool(d)
False
>>> d['foo'] = 'bar'
>>> bool(d)
True
>>> s = str(d) if d else ''
>>> s
"{'foo': 'bar'}"
>>> d = {}
>>> s = str(d) if d else ''
>>> s
''
如果你不需要在字典中有内容时将s
作为字典的字符串,只需使用 if not d: s = ''
。
任何对象都可以进行真值测试,用于if
或while
条件中,或作为下面布尔操作的操作数。以下值被认为是假的:
None
False
0
、0.0
、0j
。''
、()
、[]
。{}
。__bool__()
或__len__()
方法,并且该方法返回整数零或bool
值False
,则用户定义的类的实例也被认为是假的。因此,根据加粗的规则,您的空字典实际上是False
。所以您可以使用:
d = {}
if not d:
s = ''
else:
s = str(d)
将字典中的每个项目转换为字符串,然后用空字符串连接它们。
>>> ''.join(map(str,d))
__str__
方法:class DontForgetToDoYourTaxes(dict):
def __str__(self):
return self or ""
然后使用:
d = DontForgetToDoYourTaxes()
print d # ""
d["ayy"] = "lmao"
print d # "{'ayy': 'lmao'}"