gpt4 book ai didi

Python 子字符串替换

转载 作者:行者123 更新时间:2023-11-30 23:31:16 24 4
gpt4 key购买 nike

我需要替换主字符串中的子字符串

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 没有被替换??..

最佳答案

您正在遍历字符串,但这并没有达到您的预期。迭代字符串会遍历每个字符。

您需要做的是:

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"。请注意开头的引号。

关于Python 子字符串替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20042241/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com