将空字典转换为空字符串 [英] Convert empty dictionary to empty string

查看:86
本文介绍了将空字典转换为空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

>>> d = {}
>>> s = str(d)
>>> print s
{}

我需要一个空字符串.

推荐答案

由于空字典为False,因此可以通过以下最短的方法进行操作,并通过

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

或者没有str

>>> d = {}
>>> d or ''
''

如果d不是空字典,请使用str()

If d is not an empty dictionary, convert it to string with str()

>>> d['f'] = 12
>>> str(d or '')
"{'f': 12}"

这篇关于将空字典转换为空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆