我需要编写一个函数,其中包含一个字符串(str)、另外两个字符串(称为replace1和replace2)和一个整数(n)。该函数将返回一个新字符串,其中来自replace1的所有字符串输入都位于第一个字符串(str)中,并根据需要新输入的位置将新字符串替换为replace1。我不应该使用内置函数,但我可以使用lens(我们可以假设replace1的长度为1)。示例(称为replaceChoice):
>>> replaceChoice(“Mississippi”, “s”, “l”, 2)
'Mislissippi'
我希望我解释得很好。以下是我的尝试:
def replaceChoice(str1, replace1,n):
newString=""
for x in str:
if x=="str1":
newString=newString+replace
else:
newString=newString+x
return newString
根据你的问题,我假设你想用r2替换r1的第n次出现。 这就是你想要的吗?你知道吗
相关问题 更多 >
编程相关推荐