在Python中动态查找替换字符串内容
我需要在一个字符串中找到特定的模式,并用动态生成的内容替换它们。
假设我想找到字符串中所有用单引号包围的内容,并把这些内容重复一遍。比如说:
我的 '猫' 是 '白色'
应该变成 我的 '猫猫' 是 '白色白色'
而且这些匹配的内容可能在字符串中出现两次。
谢谢!
2 个回答
1
在你的情况下,其实不使用正则表达式也很简单:
s = "my 'cat' is 'white'".split("'")
# the parts between the ' are at the 1, 3, 5 .. index
print s[1::2]
# replace them with new elements
s[1::2] = [x+x for x in s[1::2]]
# join that stuff back together
print "'".join(s)
7
利用一下正则表达式的强大功能。在这个特定的例子中:
import re
s = "my 'cat' is 'white'"
print re.sub("'([^']+)'", r"'\1\1'", s) # prints my 'catcat' is 'whitewhite'
\1
指的是正则表达式中的第一个分组(在其他一些实现中叫做$1
)。