0

这是一个家庭作业问题。我正在定义一个函数,它接受一个单词并将给定的字符替换为另一个字符。例如 replace("cake","a","o") 应该返回我试过的 "coke"

def replace(word,char1,char2):
    newString = ""
    for char1 in word:
        char1 = char2
        newString+=char1
    return newString  #returns 'oooo'

def replace(word,char1,char2):
    newString = ""
    if word[char1]:
        char1 = char2
        newString+=char1
    return newString  #TypeError: string indices must be integers, not str

我假设我的第一次尝试更接近我想要的。我的功能出了什么问题?

4

2 回答 2

3

Try this:

def replace(word,char1,char2):
    newString = ""
    for next_char in word:         # for each character in the word
        if next_char == char1:     # if it is the character you want to replace
            newString += char2     # add the new character to the new string
        else:                      # otherwise
            newString += next_char # add the original character to the new string
    return newString

Although strings in python already have a method that does this:

print "cake".replace("a", "o")
于 2013-03-22T03:35:19.563 回答
2
def replace(word, ch1, ch2) :
    return ''.join([ch2 if i == ch1 else i for i in word])
于 2013-03-22T03:46:09.977 回答