请教一个关于 Python repr 方法的问题

barantt01 · 2025-1-14 16:41:11 · 430 次点击

示例代码如下

tmp = '{"{\"username\":\"juheso\",\"is_cache\":1}":3}'
print(tmp)
print(repr(tmp))
tmp_1 = r'{"{\"username\":\"juheso\",\"is_cache\":1}":3}'
print(tmp_1)

我运行之后的结果为

{"{"username":"juheso","is_cache":1}":3}
'{"{"username":"juheso","is_cache":1}":3}'
{"{\"username\":\"juheso\",\"is_cache\":1}":3}

我想要的结果其实是{"{\"username\":\"juheso\",\"is_cache\":1}":3}

但是为什么 repr() 没有效果呢?

我的 python 版本为 3.10

举报· 430 次点击
登录 注册 站外分享
3 条回复  
superrichman 小成 2025-1-14 16:48:43
仔细琢磨 print('\"' == '"') print(r'\"' == '\\"')
barantt01 楼主 初学 2025-1-14 17:09:04
@superrichman 这两个都是 True 我知道,我的疑问是在 repr 方法上。因为在实际使用是这个 tmp 其实是一个变量,没法用 r''来表示
eccstartup 初学 2025-1-14 17:55:19
```python import json s = '{"{\"username\":\"juheso\",\"is_cache\":1}":3}' raw_s = json.dumps(s)[1:-1] print(raw_s) # 输出: "Hello\\nWorld" ``` 输出 `{\"{\"username\":\"juheso\",\"is_cache\":1}\":3}` 比较接近了
返回顶部