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

Python :strip()方法的正则表达式余运算判断传参

  •  
  •   CalmSea · 2022-03-07 12:45:52 +08:00 · 2256 次点击
    这是一个创建于 790 天前的主题,其中的信息可能已经有所发展或是发生改变。

    题目: 写一个函数,它接受一个字符串,做的事情和 strip()字符串方法一样。如果只传入了要去除的字符串,没有其他参数,那么就从该字符串首尾去除空白字符。否则,函数第二个参数指定的字符将从该字符串中去除。

    问题: 这一行 % (t, t) 是如何起作用的, 原理是如何?

    
    import re
    ​
    def re_strip(s, t=r'\s'):
        t_format = r'^%s*|%s*$' % (t, t)
        s_re = re.compile(t_format)
        s = s_re.sub('',s)
        return s
    ​
    print(re_strip('aadasdfsaaa','a'))
    print(re_strip('  dafsdfa sadfasd  '))
    
    
    4 条回复    2022-03-08 18:36:19 +08:00
    ChrisFreeMan
        1
    ChrisFreeMan  
       2022-03-07 12:51:43 +08:00
    这是字符串格式化,替换里面的%s ,其实现在已经没人这么写了都用 f 操作符字符串格式化了
    CalmSea
        2
    CalmSea  
    OP
       2022-03-07 13:01:53 +08:00
    懂了,感谢.
    Vegetable
        3
    Vegetable  
       2022-03-07 13:04:18 +08:00
    python 之前的字符串格式方法。现在没什么人用了
    frostming
        4
    frostming  
       2022-03-08 18:36:19 +08:00
    插句题外话,要用正则复制 strip()的行为需要把两个 %s 用 [ ] 包裹下
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   761 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 20:30 · PVG 04:30 · LAX 13:30 · JFK 16:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.