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

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

  •  
  •   lailongmen · 2018-06-14 00:11:33 +08:00 · 2218 次点击
    这是一个创建于 2115 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 条回复    2018-06-18 17:13:04 +08:00
    hubqin
        1
    hubqin  
       2018-06-14 00:32:26 +08:00
    这样改就可以了:
    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  
       2018-06-14 09:51:36 +08:00
    真心看不下去了。
    求求楼主,能把
    w=re.findall(r'%s'% x,txt)
    改成
    w=re.findall(repr(x), txt)
    么?

    还有就是把 x 当参数传进来,弄成全局变量太恶心了。
    lailongmen
        3
    lailongmen  
    OP
       2018-06-18 17:13:04 +08:00
    @hubqin 谢谢!可以了。

    @xpresslink 你这个方法不行啊。我是新手在看教学,只会这个办法。
    教学里面是固定内容,比如:re.findall(r"hi", text)
    感觉那样太死板,所以自己改成变量。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   994 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 22:16 · PVG 06:16 · LAX 15:16 · JFK 18:16
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.