以编程方式在python中的字符串中动态查找和替换内容

时间:2010-10-05 22:47:07

标签: python replace

我需要使用动态生成的内容来查找和替换字符串中的模式。

假设我想找到字符串中''内的所有字符串并将字符串加倍。 一个字符串,如:

my 'cat' is 'white'应该成为我的'catcat' is 'whitewhite'

所有匹配也可以在字符串中出现两次。

谢谢

2 个答案:

答案 0 :(得分:7)

利用regular expressions的力量。在这种特殊情况下:

import re

s = "my 'cat' is 'white'"

print re.sub("'([^']+)'", r"'\1\1'", s) # prints my 'catcat' is 'whitewhite'

\1指的是正则表达式中的第一个组(在其他一些实现中称为$1)。

答案 1 :(得分: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)