没有任何导入或内置函数的替换方法?
这是一个作业问题。我正在定义一个函数,这个函数可以把一个单词中的某个字符替换成另一个字符。例如,调用 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
我觉得我的第一次尝试更接近我想要的结果。我的函数哪里出错了呢?
2 个回答
2
在编程中,有时候我们需要处理一些数据,比如从一个地方获取数据,然后把它放到另一个地方。这就像把水从一个杯子倒到另一个杯子一样。
在这个过程中,我们可能会遇到一些问题,比如数据格式不对,或者数据不完整。这就像你在倒水的时候,发现杯子有个洞,水会漏掉一样。
为了避免这些问题,我们可以使用一些工具和方法来确保数据的正确性和完整性。这就像在倒水之前,先检查一下杯子有没有破损。
总之,处理数据的时候要小心,确保每一步都做得对,这样才能得到我们想要的结果。
def replace(word, ch1, ch2) :
return ''.join([ch2 if i == ch1 else i for i in word])
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")