V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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
lailongmen
V2EX  ›  Python

请问: re.findall 使用变量,变量内容中的“\b”不起作用咋办?

  •  
  •   lailongmen · Jun 14, 2018 · 2828 views
    This topic created in 2878 days ago, the information mentioned may be changed or developed.
    import re
    def find():
    txt = 'Hi, I am Shirley Hilton. I am his wife.'
    w=re.findall(r'%s'% x,txt)
    if w:
    print(w)
    else:
    print('not match')

    x='hi'
    find()
    x='Hi'
    find()
    x='\bhi\b'
    find()

    输出结果:
    前面 2 个正常,后面这个 x='\bhi\b'就不对了。
    3 replies    2018-06-18 17:13:04 +08:00
    hubqin
        1
    hubqin  
       Jun 14, 2018
    这样改就可以了:
    import re
    def find():
    txt = ' hi , I am Shirley Hilton. I am his wife.'
    w=re.findall('%s' % x,txt)
    if w:
    print(w)
    else:
    print('not match')

    x='hi'
    find()
    x='Hi'
    find()
    x=r'\bhi\b'
    find()
    xpresslink
        2
    xpresslink  
       Jun 14, 2018
    真心看不下去了。
    求求楼主,能把
    w=re.findall(r'%s'% x,txt)
    改成
    w=re.findall(repr(x), txt)
    么?

    还有就是把 x 当参数传进来,弄成全局变量太恶心了。
    lailongmen
        3
    lailongmen  
    OP
       Jun 18, 2018
    @hubqin 谢谢!可以了。

    @xpresslink 你这个方法不行啊。我是新手在看教学,只会这个办法。
    教学里面是固定内容,比如:re.findall(r"hi", text)
    感觉那样太死板,所以自己改成变量。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1094 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 50ms · UTC 23:46 · PVG 07:46 · LAX 16:46 · JFK 19:46
    ♥ Do have faith in what you're doing.