Python子串替换

时间:2013-11-18 07:22:56

标签: python string

我需要替换主字符串

中的子字符串
mainstr='"Name":"xxx","age":"{"This":"has to","be":"replaced"}","dept":"cse"'
substr='"{"This":"has to","be":"replaced"}"'

期望的输出:

mainstr="Name:xxx","age":"checked","dept":"cse"

我尝试了以下代码:

for substr in mainstr:

    mainstr=mainstr.replace(substr,"checked")
    print "Output=",mainstr

执行后,

Output="Name:xxx","age":"{This":"has to","be":"replaced"}","dept":"cse"   

为什么substr没有被替换?? ..

1 个答案:

答案 0 :(得分:3)

您正在遍历字符串,这不符合您的期望。迭代字符串会遍历每个字符。

您需要做的就是:

mainstr = '"Name:xxx","age":"{This":"has to","be":"replaced"}","dept":"cse"'
substr = '{This":"has to","be":"replaced"}'
print "Output = ", mainstr.replace(substr, 'checked')
#                ^ The comma here is important.

注意:代码不适合您,因为substr = '"{This而非substr = '{This"。注意开头的引号。

相关问题