-1

我已经编写了一个替换所有“X”实例的函数,但是我如何让它只在从开始到停止的间隔内替换它?

def replaceSegment(string, replace, start, stop):
    newstring = ''
    for x in string:
        if x == 'X':
            newstring = newstring + replace
        else:
            newstring = newstring + x
    return newstring

编写一个函数replaceSegment,它接受一个字符串str和另一个字符串replace,以及两个整数start和stop。该函数应返回一个新字符串,其中原始字符串 str 中所有出现的子字符串“X”,在从索引开始到但不包括索引停止的范围内,都被替换字符串替换。

执行相同或相似任务的内置函数或模块,不在此任务中使用。但是,允许使用 len() 函数。

例子:

ReplaceSegment >>> ("HXej! BalXoo X", "hope", 3, 7)
'HXej! Hope balXoo! ')
4

1 回答 1

0

start把字符串想象stop成三部分:

  • 第一部分从字符串的开头开始,在之前结束start
  • 第二个开始start并结束于之前stop
  • 第三个开始于stop字符串的末尾。

所以,只有第二部分被改变了。

如果您可以成功隔离这三个部分,则可以从newstring第一部分开始,仅将循环应用于第二部分,然后在最后添加最后一部分。它看起来像这样:

def replaceSegment(string, replace, start, stop):
    # before  = the part of string before start
    # segment = the part of string from start to before stop
    # after = the part of the string from stop to the end of string
    newstring = before
    for x in segment:
        if x == 'X':
            newstring = newstring + replace
        else:
            newstring = newstring + x

    newstring += after
    return newstring
于 2013-10-31T12:57:37.410 回答