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

2018-06-14 00:11:33 +08:00
 lailongmen
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'就不对了。
2243 次点击
所在节点    Python
3 条回复
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
2018-06-14 09:51:36 +08:00
真心看不下去了。
求求楼主,能把
w=re.findall(r'%s'% x,txt)
改成
w=re.findall(repr(x), txt)
么?

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

@xpresslink 你这个方法不行啊。我是新手在看教学,只会这个办法。
教学里面是固定内容,比如:re.findall(r"hi", text)
感觉那样太死板,所以自己改成变量。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/462936

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX