python - 替换字符串 Python

标签 python

试图完全按照我的 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/

相关文章:

python - 如何将带有列表作为值的Python字典展开为带有两个元素的键值元组列表?

python - 以欧洲格式显示 pandas 数据框

python - 播放 WAV 歌曲时机器人不跳舞

python - 如何使用 Python 中的 Paramiko 库在 SFTP 上将 Pandas DataFrame 传输到 .csv?

python - 在 Windows 上 pip install django mysqlclient 'path should be string, bytes, os.PathLike or integer, not NoneType'

python - 如何在 SymPy 中定义数学函数?

python - 如何为请求库创建嵌套参数

python - 我正在更改一个变量,但是如何在函数结束时返回它的原始状态?

python - 是否可以使用 Python 异步发送许多请求

python - 远程 python 和 django 控制台在更新到 3.1 后不起作用