Python在“”之间的字符串中查找单词
我想搜索并替换两个标记之间的单词 文本是用户随机添加的Python在“”之间的字符串中查找单词,python,Python,我想搜索并替换两个标记之间的单词 文本是用户随机添加的 example = 'hello this #word1# a it #word2# thanks!' text = "hello this #word1# a it #word2# thanks!" 我需要在word1和word2之间删去这两个单词,并用大写字母-.title替换第一个字母 我有一个密码: import re text = 'hello this #word1# a it #word2# thanks!' print
example = 'hello this #word1# a it #word2# thanks!'
text = "hello this #word1# a it #word2# thanks!"
我需要在word1和word2之间删去这两个单词,并用大写字母-.title替换第一个字母
我有一个密码:
import re
text = 'hello this #word1# a it #word2# thanks!'
print re.sub('#(\w+)#', lambda m:m.group(1).title(), text)
输出:您好这个词1 a it词2谢谢
如何输出:您好,这个单词1,it单词2,谢谢 你是说像这样
>>> print re.sub('(#\w+#)', lambda m:m.group(1).title(), text)
hello this #Word1# a it #Word2# thanks!
只需扩展组,就可以包含以下字符:
print re.sub('(#\w+#)', lambda m:m.group(1).title(), text)
您可以使用断言:
>>> re.sub('(?<=#)(\w+)(?=#)', lambda m:m.group(1).title(), text)
hello this #Word1# a it #Word2# thanks!
向函数中添加
import re
text = 'hello this #word1# a it #word2# thanks!'
print re.sub('#(\w+)#', lambda m: "#" + m.group(1).title() + "#", text)
使用group0而不是group1
import re
text = 'hello this #word1# a it #word2# thanks!'
print re.sub('#(\w+)#', lambda m:m.group(0).title(), text)
lambda m:+m.group1.title+。看起来你不明白你在做什么,为什么它会这样工作。请花些时间研究您正在使用的语言的基础知识。@J0HN虽然这会返回此特定情况的预期答案,但它在设计上有一个缺点:函数和正则表达式是耦合的,必须一起更改。当逻辑和常量分别定义时,这会中断代码连接。该代码是正确的。您使用的是哪个版本的Python?group0表示整个匹配字符串,group1表示括号内的匹配。