試圖完成我的doctsring說什麼,但我有一個問題。在我的一個輸出結果中,我無法弄清楚發生了什麼問題。替換字符串Python
#Replace String
def replace_str(op1,op2,op3):
"""Returns the string which is a copy of the first parameter, but where \
all occurrences of the second parameter have been replaced by the third\
parameter"""
finalword=""
if op2 not in op1:
return op1
if op2 == "":
finalword+=op3
for i in op1:
finalword+=i+op3
return finalword
count=0
for i, ch in enumerate(op1):
count+=1
sliceword=op1[i:i+len(op2)]
if sliceword == op2:
count = len(op2)
finalword+=op3
else:
finalword+=ch
count-=1
return final word
輸出:
g=replace_str("Hello World","o","test")
print("Hello World, o, test, returns:",g)
Hello World, o, test, returns: Helltest Wtestrld
g1=replace_str("Hello","o"," is not fun")
print("Hello, o, is not fun, returns:",g1)
Hello, o, is not fun, returns: Hell is not fun
g5=replace_str("HelloWorld","World","12345")
print("HelloWorld, World, 12345, returns:",g5)
HelloWorld, World, 12345, returns: Hello12345orld
一個你可以看到HelloWorld, World, 12345
,我得到Hello12345orld
。我期望的輸出是Hello12345
你在做這個作爲一個練習?因爲如果我理解正確,你似乎正在複製內置的'str.replace'。 – 2015-03-02 22:48:02
您的第三個輸出與您的輸出結果不匹配。 – levi 2015-03-02 22:49:04
感謝捕捉,我只是改變了@levi – Charlie 2015-03-02 22:51:58