推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
barantt01
V2EX  ›  Python

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

  •  
  •   barantt01 · Jan 14, 2025 · 5667 views
    This topic created in 667 days ago, the information mentioned may be changed or developed.

    示例代码如下

    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

    8 replies  •  2025-01-16 22:23:36 +08:00
    superrichman
    superrichman
    Jan 14, 2025
    1
    仔细琢磨

    print('\"' == '"')
    print(r'\"' == '\\"')
    barantt01
    barantt01
    OP
    Jan 14, 2025
    2
    @superrichman 这两个都是 True 我知道,我的疑问是在 repr 方法上。因为在实际使用是这个 tmp 其实是一个变量,没法用 r''来表示
    eccstartup
    eccstartup
    Jan 14, 2025
    3
    ```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}`

    比较接近了
    julyclyde
    julyclyde
    Jan 14, 2025
    4
    你这个不是 repr 方法而是 repr 函数
    ma46
    ma46
    Jan 15, 2025
    5
    @julyclyde 内置函数 repr 调用的就是对象的__repr__方法
    ma46
    ma46
    Jan 15, 2025
    6
    对于 tmp 变量, 其内存里存的字符串就是{"{"username":"juheso","is_cache":1}":3}, 你还想 repr 输出什么东西来? 变量赋值里的 \ 根本就不是字符串的一部分, 它的作用是告诉编译器 " 是字符串的一部分

    我觉得你还没理解转义字符
    julyclyde
    julyclyde
    Jan 15, 2025
    7
    @ma46 我知道啊。但是提问是方法而非函数这个错误依然是存在的
    lijiachang
    lijiachang
    Jan 16, 2025
    8
    tmp = r'{"{\"username\":\"juheso\",\"is_cache\":1}":3}'
    print(tmp)

    声明的时候就要加 r ,否则你就写个转换函数
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2530 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 11:52 · PVG 19:52 · LAX 03:52 · JFK 06:52
    ♥ Do have faith in what you're doing.