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
frogs
V2EX  ›  Python

问个关于raw string的问题

  •  
  •   frogs · 2013-02-18 20:32:07 +08:00 · 3293 次点击
    这是一个创建于 4098 天前的主题,其中的信息可能已经有所发展或是发生改变。
    不知道有没有便捷的将string 转换成raw string的方法
    比如:将正则表达式"\d+(123)\s" 转换成 等同于r'\d+(123)\s'效果的raw string
    7 条回复    1970-01-01 08:00:00 +08:00
    frogs
        1
    frogs  
    OP
       2013-02-18 21:29:01 +08:00
    额 人工置顶 跪求解答 m(_ _)m
    keakon
        2
    keakon  
       2013-02-18 22:19:51 +08:00   ❤️ 2
    >>> `"\d+(123)\s"`
    "'\\\\d+(123)\\\\s'"
    >>> repr("\d+(123)\s")
    "'\\\\d+(123)\\\\s'"

    这个?
    reorx
        3
    reorx  
       2013-02-18 22:26:37 +08:00
    不需要转换呀

    >>> '\d+(123)\s' is r'\d+(123)\s'
    True
    clowwindy
        4
    clowwindy  
       2013-02-18 22:47:51 +08:00   ❤️ 1
    >>> codecs.decode(r'a\n','string_escape')
    'a\n'
    >>> codecs.encode(r'a\n','string_escape')
    'a\\\\n'
    frogs
        5
    frogs  
    OP
       2013-02-18 23:05:22 +08:00
    @keakon 我sb了,本来想问的是怎么把 字符串里面正则字符变成普通字符,
    "\d+(123)\s" 变成 r"\\d\+\(123\)\\s"这种
    keakon
        6
    keakon  
       2013-02-18 23:49:42 +08:00
    >>> print re.escape('\d+(123)\s')
    \\d\+\(123\)\\s

    这个?
    frogs
        7
    frogs  
    OP
       2013-02-18 23:58:11 +08:00
    @keakon 非常感谢,我得去扒一扒escape的src了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2647 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 15:50 · PVG 23:50 · LAX 08:50 · JFK 11:50
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.