替换String Python

时间:2015-03-02 22:45:44

标签: 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

2 个答案:

答案 0 :(得分:3)

如果匹配,你在输入字符串中没有正确前进,注意我是如何用一段时间改变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)

答案 1 :(得分:2)

您可以使用str.replace

>>> "Hello World".replace("o","test")
'Helltest Wtestrld'
  

str.replace(old,new [,count])

     

返回字符串的副本,其中所有出现的substring old都替换为new。如果给出了可选参数计数,则仅替换第一次计数出现次数。

如果你想重新创建一个,请尝试pythonic:

>>> def str_replace(my_string, old, new):
...     return "".join(new if x == old else x for x in my_string)
...
>>> str_replace("Hello World", 'o', 'test')
'Helltest Wtestrld'

在上面的代码中,您可以使用str.lower来处理区分大小写的