这是一个家庭作业问题。我正在定义一个函数,它接受一个单词并用另一个char替换给定的char。例如,替换(“蛋糕”,“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 :(得分: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")
答案 1 :(得分:2)
def replace(word, ch1, ch2) :
return ''.join([ch2 if i == ch1 else i for i in word])