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

请教 Python 正则替换字符串正确成功的姿势?

  •  
  •   uti6770werty · 2020-02-11 17:40:14 +08:00 · 2244 次点击
    这是一个创建于 1551 天前的主题,其中的信息可能已经有所发展或是发生改变。
    [17:31:27]
    

    时间字符,想替换成用"$"符号包裹起来
    像这样:

    $[17:31:27]$
    

    TimeStr = "[17:31:27]"
    TimeStr = re.sub(r"\[\d+:\d+:\d+\]",r"$\1$",TimeStr )
    

    TtimeStr 出来是个空白的字符。。。

    5 条回复    2020-02-13 14:38:18 +08:00
    gwy15
        1
    gwy15  
       2020-02-11 17:55:14 +08:00
    ```
    re.sub(r"(\[\d+:\d+:\d+\])",r"$\1$", s)
    ```
    ipwx
        2
    ipwx  
       2020-02-11 17:56:19 +08:00
    你都没有 group[1],你这句话是怎么执行成功的。。。3.6 直接报错。

    re.sub(r"(\[\d+:\d+:\d+\])",r"$\1$", "[17:31:27]")
    uti6770werty
        3
    uti6770werty  
    OP
       2020-02-11 19:31:25 +08:00
    @gwy15 成了,谢谢~
    @ipwx 抱歉,我发帖的时候改回了 r",我在测试的时候用的是 u"...[机械狗头]
    ps1aniuge
        4
    ps1aniuge  
       2020-02-12 15:59:50 +08:00   ❤️ 1
    “[”替换成"$[",不就完了么?
    deplives
        5
    deplives  
       2020-02-13 14:38:18 +08:00
    同楼上,如果格式固定,直接 replace("[","$[") replace("]","]$") 不比正则好使
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2684 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 05:56 · PVG 13:56 · LAX 22:56 · JFK 01:56
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.