python - __str__ 和 Python 中的单引号与双引号行为

标签 python quotes

如果我定义一个带有字符串的字典

d = {"5": 5}

用单引号打印显示

>> print d
>> {'5': 5}

有没有办法让它用双引号打印出来?

编辑:

完整的故事是我最初将树定义为嵌套字典并使用 json 在语言之间传输它。然后我决定将字典包装在一个类中,但这破坏了我在 json 中对其进行编码的方法。

最佳答案

是的(假设你有 json 模块):

>>> import json
>>> print json.dumps({'5': 5})
{"5": 5}
>>> 

关于使用 print 时的引号数,Python docs说:

The string is enclosed in double quotes if the string contains a single quote and no double quotes, else it’s enclosed in single quotes.

关于python - __str__ 和 Python 中的单引号与双引号行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9830522/

相关文章:

mysql - MySQL 中何时使用单引号、双引号和反引号

c# - 遍历双引号但忽略单引号中的双引号

python - SyntaxError : multiple statements found in python. 有人有这方面的经验吗?

MySQL 5.7 JSON_EXTRACT 不适用于对象 : [ERROR] "Missing a closing quotation mark in string" 中带引号的字符串

python - 如何通过 python 多处理填充数组?

python - Pandas 分类错误 : "Cannot setitem on a Categorical with a new category, set the categories first"

bash - Bash 中单引号和双引号的区别

PHP 单引号与双引号

python - Pandas 重采样/TimeGrouper 中的错误

python - 我可以让 Python 准确地告诉我哪个字符导致错误吗?