2013-03-22 38 views
0

這是一個家庭作業問題。我正在定義一個函數,它接受一個字並用另一個字符替換給定的字符。例如替換(「蛋糕」,「A」,「O」)應該返回「可樂」我曾嘗試更換沒有任何進口或內置函數?

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 

我假設我第一次嘗試是接近到什麼我想要。我的功能出了什麼問題?

+0

您不必檢查,看何時更換字符。所以在你的第一個函數中加入'if'' else' – jamylak 2013-03-22 03:34:05

回答

3

試試這個:

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 

雖然在Python中已經有做這個的方法:

print "cake".replace("a", "o") 
2
def replace(word, ch1, ch2) : 
    return ''.join([ch2 if i == ch1 else i for i in word]) 
相關問題