python如何工作:字符串在python中如何替换?

2024-06-16 10:11:58 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的示例中,为什么不替换第一个“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公司

hurt, hurt heart

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

Tags: 示例onlysongitbereplaceprintlet