首页 > 解决方案 > python:python 中的 string.replace() 是如何工作的?

问题描述

在下面的示例中,为什么不替换第一个“让”而不是替换第二个和第三个。谁能帮我为什么选择第二和第三而不是第一和第二'让'?

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

标签: pythonstringmethodsoutput

解决方案


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


推荐阅读