试图完全按照我的 doctsring 所说的去做,但我遇到了一个问题。在我的一个输出中,我无法弄清楚出了什么问题。
#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
最佳答案
在匹配的情况下,您没有在输入字符串中正确前进,请注意我是如何更改 for 循环的:
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
i = 0
while i < len(op1):
sliceword=op1[i:i+len(op2)]
if sliceword == op2:
finalword+=op3
i += len(op2)
else:
finalword+=op1[i]
i += 1
return finalword
g=replace_str("Hello World","World","test")
print("Hello World, o, test, returns:",g)
关于python - 替换字符串 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28820857/