V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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
aheadlead
V2EX  ›  Python

如何对字符串进行反转义,如"\r\n"得到"\\r\\n",谢

  •  
  •   aheadlead · 2014-12-11 12:55:21 +08:00 · 8122 次点击
    这是一个创建于 3417 天前的主题,其中的信息可能已经有所发展或是发生改变。
    8 条回复    2014-12-11 15:18:24 +08:00
    tomriddle
        1
    tomriddle  
       2014-12-11 12:59:14 +08:00   ❤️ 1
    import re
    re.escape('\\r\\n')
    iptux
        2
    iptux  
       2014-12-11 13:01:53 +08:00   ❤️ 2
    ```
    $ python
    Python 2.7.3 (default, Feb 27 2014, 19:58:35)
    [GCC 4.6.3] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> '\r\n'.encode('string_escape')
    '\\r\\n'
    >>>
    ```

    hex 的 encoding 也很好用
    aheadlead
        3
    aheadlead  
    OP
       2014-12-11 13:05:14 +08:00   ❤️ 1
    @iptux 成功了!感谢
    banbanchs
        4
    banbanchs  
       2014-12-11 13:05:43 +08:00
    s.encode("unicode_escape") ?
    staticor
        5
    staticor  
       2014-12-11 13:05:52 +08:00
    repr(s).replace('\\', '\\\\')
    jiankangxin
        6
    jiankangxin  
       2014-12-11 13:10:15 +08:00
    @iptux 之前一直在用 replace 原来。。。
    kungfuchicken
        7
    kungfuchicken  
       2014-12-11 13:12:20 +08:00
    "\\".join(r'\r\n'.split("\\"))
    lygmqkl
        8
    lygmqkl  
       2014-12-11 15:18:24 +08:00
    我都是在 js层做这个 转换得,感觉存入数据库得时候改变并不是很好。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   953 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 19:50 · PVG 03:50 · LAX 12:50 · JFK 15:50
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.