示例代码如下
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
1 superrichman 268 天前 仔细琢磨 print('\"' == '"') print(r'\"' == '\\"') |
![]() | 2 barantt01 OP @superrichman 这两个都是 True 我知道,我的疑问是在 repr 方法上。因为在实际使用是这个 tmp 其实是一个变量,没法用 r''来表示 |
![]() | 3 eccstartup 268 天前 ```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}` 比较接近了 |
4 julyclyde 268 天前 你这个不是 repr 方法而是 repr 函数 |
![]() | 6 ma46 267 天前 对于 tmp 变量, 其内存里存的字符串就是{"{"username":"juheso","is_cache":1}":3}, 你还想 repr 输出什么东西来? 变量赋值里的 \ 根本就不是字符串的一部分, 它的作用是告诉编译器 " 是字符串的一部分 我觉得你还没理解转义字符 |
![]() | 8 lijiachang 266 天前 tmp = r'{"{\"username\":\"juheso\",\"is_cache\":1}":3}' print(tmp) 声明的时候就要加 r ,否则你就写个转换函数 |