python - 将空字典转换为空字符串

标签 python string dictionary

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

我需要一个空字符串。

最佳答案

你可以用最短的方式完成,因为空字典是False,通过Boolean Operators完成。 .

>>> d = {}
>>> str(d or '')
''

或者没有str

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

如果d不是一个空字典,用str()将它转换成字符串

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

关于python - 将空字典转换为空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35389648/

相关文章:

string - 如何将字符串选项合并到 fsharp 中的单个字符串选项?

python - 如何为每个列类别创建数据框字典

python - 按键列表过滤/分组字典列表

javascript - 如何将 Python 字典序列化为 JavaScript 对象文本?

python - 有没有办法使用 pyqt 将(动画)GIF 图像作为系统托盘图标?

python - 如何在 Pandas 的列中删除不包含字符串类型的行?

c++ - 二维数组重载

python argh/argparse : How can I pass a list as a command-line argument?

python - 返回 pandas df 中值的运行计数

c - C 中缺少访问说明符 & 不会导致编译错误