替换输入字符串和整数

2024-09-30 12:31:29 发布

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

我需要编写一个函数,其中包含一个字符串(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

Tags: 函数字符串示例def整数内置lensstr
1条回答
网友
1楼 · 发布于 2024-09-30 12:31:29

根据你的问题,我假设你想用r2替换r1的第n次出现。 这就是你想要的吗?你知道吗

>>> def replaceChoice(str1, r1, r2, n):
...     new_str = ""
...     replaced = False
...     for i in str1:
...             if i==r1:
...                     n-=1
...             if n==0 and not replaced:
...                     replaced = True
...                     new_str+=r2
...             else:
...                     new_str+=i
...     return new_str
... 
>>> replaceChoice("Mississippi", "s", "l", 2)
'Mislissippi'

相关问题 更多 >

    热门问题