Python 如何编写函数来替换对象?

Python 如何编写函数来替换对象?,python,python-2.7,replace,str-replace,Python,Python 2.7,Replace,Str Replace,我正试图用python完成一项作业,我完全被难住了。请帮忙 编写一个名为myReplace的函数,该函数执行类似于string.replace方法的任务。此函数应具有三个参数:第一个参数称为内容字符串,可以是任何字符串。第二个标记应该是一个字符串,其中包含一个要在内容字符串中替换的字符。第三个字符应该表示结果字符串中的新字符。函数应返回一个新字符串,其中标记字母替换为新字符。函数应该确保提供了有效的输入,如果没有,则返回原始字符串。注意:此问题不能使用内置的替换方法。 例如: 我不想让任何人为我

我正试图用python完成一项作业,我完全被难住了。请帮忙

编写一个名为myReplace的函数,该函数执行类似于string.replace方法的任务。此函数应具有三个参数:第一个参数称为内容字符串,可以是任何字符串。第二个标记应该是一个字符串,其中包含一个要在内容字符串中替换的字符。第三个字符应该表示结果字符串中的新字符。函数应返回一个新字符串,其中标记字母替换为新字符。函数应该确保提供了有效的输入,如果没有,则返回原始字符串。注意:此问题不能使用内置的替换方法。 例如:

我不想让任何人为我写这封信。但我不知道该怎么办

def myReplace(s,old,new): new.join(s.split(old))
是你想要的小版本。您将需要添加错误检查和所有类似类型或lenold的内容,然后在必要时返回s

def replace(stringname,oldletter,newletter):
    newstring = ''
    for i in range(len(stringname)):
        if stringname[i] == oldletter:
            newstring = newstring + newletter
        else:
            newstring = newstring + stringname[i]
    return newstring

stringorig = "Hello World!"
displayname = replace(stringorig,'l','o')
print displayname

获取字符串的索引,并将其与需要将其更改为的字母进行比较。我相信R Nar的答案是最短和最好的答案,但更多答案也不会有什么坏处。

我们可以看看您当前的myReplace函数吗?允许您使用正则表达式吗?提示:尝试将字符串分配给变量repstring=Hello World,看看在执行repstring[0]时会发生什么。请查看相关的find、rfind、index、,和rindex.myReplace=lambda c,t,r:.加入[x,r][x==t]对于c中的x,对于初学者来说,一件好事情是打开课本,上课,做笔记,如果你不理解概念,向老师或同学提问。。。否则,基于这个概念的未来课程将锁定在你的大脑中
def replace(stringname,oldletter,newletter):
    newstring = ''
    for i in range(len(stringname)):
        if stringname[i] == oldletter:
            newstring = newstring + newletter
        else:
            newstring = newstring + stringname[i]
    return newstring

stringorig = "Hello World!"
displayname = replace(stringorig,'l','o')
print displayname