2015-03-02 215 views
1

試圖完成我的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

+3

你在做這個作爲一個練習?因爲如果我理解正確,你似乎正在複製內置的'str.replace'。 – 2015-03-02 22:48:02

+1

您的第三個輸出與您的輸出結果不匹配。 – levi 2015-03-02 22:49:04

+0

感謝捕捉,我只是改變了@levi – Charlie 2015-03-02 22:51:58

回答

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) 
2

您可以使用str.replace

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

str.replace(舊的,新[,計數])

返回一個字符串的所有Ø副本舊字符串的發生由新字符替換。如果給出可選的參數計數,則僅替換第一個計數事件。

如果要重新創建一個,嘗試Python的:

>>> 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處理區分大小寫

+1

OP是不是要求一個內置的功能。他正在嘗試重新創建它。 – levi 2015-03-02 22:53:44

+1

@levi練習顯示OP需要關注str.replace。該合作伙伴看起來像那樣 – Hackaholic 2015-03-02 22:55:08

+0

如果OP想重新創造它,那我的朋友永遠不會浪費時間。 – levi 2015-03-02 22:57:07