推荐学习书目
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 · Mar 7, 2022 · 3011 views
    This topic created in 1543 days ago, the information mentioned may be changed or developed.

    题目: 写一个函数,它接受一个字符串,做的事情和 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 replies    2022-03-08 18:36:19 +08:00
    ChrisFreeMan
        1
    ChrisFreeMan  
       Mar 7, 2022
    这是字符串格式化,替换里面的%s ,其实现在已经没人这么写了都用 f 操作符字符串格式化了
    CalmSea
        2
    CalmSea  
    OP
       Mar 7, 2022
    懂了,感谢.
    Vegetable
        3
    Vegetable  
       Mar 7, 2022
    python 之前的字符串格式方法。现在没什么人用了
    frostming
        4
    frostming  
       Mar 8, 2022
    插句题外话,要用正则复制 strip()的行为需要把两个 %s 用 [ ] 包裹下
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   924 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 60ms · UTC 20:42 · PVG 04:42 · LAX 13:42 · JFK 16:42
    ♥ Do have faith in what you're doing.