Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python:python中string.replace()是如何工作的?_Python_String_Methods_Output - Fatal编程技术网

python:python中string.replace()是如何工作的?

python:python中string.replace()是如何工作的?,python,string,methods,output,Python,String,Methods,Output,在下面的示例中,为什么不替换第一个“let”,而替换第二个和第三个。有人能帮我解释为什么它选择第二和第三而不是第一和第二个“让”吗 song = 'cold, cold heart' print (song.replace('cold', 'hurt')) song = 'Let it be, let it be, let it be, let it be' '''only two occurences of 'let' is replaced''' print(song.replace(

在下面的示例中,为什么不替换第一个“let”,而替换第二个和第三个。有人能帮我解释为什么它选择第二和第三而不是第一和第二个“让”吗

song = 'cold, cold heart'
print (song.replace('cold', 'hurt'))

song = 'Let it be, let it be, let it be, let it be'

'''only two occurences of 'let' is replaced'''

print(song.replace('let', "don't let", 2))
o/p


string.replace()
区分大小写
“Let”
与“Let”不同,因此当方法查找出现的
“Let”
时,它会被忽略。

就是这样(因此它忽略了第一个Let),并且您使用了一个计数参数o 2Ignore-OP对first
Let
有问题,您正确地解释了这个问题。
hurt, hurt heart

Let it be, don't let it be, don't let it be, let it be