2014-02-19 45 views
-1

我是新來的python和一個練習我創建一個函數,將做與.replace方法相同。函數協助

我有這個至今:

def replace_str (string, substring, replace): 
    my_str = "" 
    for index in range(len(string)): 
     if string[index:index+len(substring)] == substring : 
      my_str += replace 
     else: 
      my_str += string[index] 
    return my_str 

測試時用:

print (replace_str("hello", "ell", "xx")) 

它返回:

hxxllo 

我希望有人能幫助我指出正確的方向以便用「xx」代替「ell」,然後跳到「o」並打印:

hxxo 

作爲.replace字符串方法會做。

+0

你可以使用正則表達式? – Drewness

+2

這些類型的練習是最糟糕的。 – wim

+0

那麼如果你不能導入任何東西,那麼正則表達式就不存在了。 – Drewness

回答

0

通常情況下,使用while用手工維護的索引變量是一個壞主意,但是當你需要操作循環中的索引,它可以是一個不錯的選擇:

def replace_str(string, substring, replace): 
    my_str = "" 
    index = 0 
    while index < len(string): 
     if string[index:index+len(substring)] == substring: 
      my_str += replace 
      # advance index past the end of replaced part 
     else: 
      my_str += string[index] 
      # advance index to the next character 
    return my_str 

注意x.replace(y, z)y爲空時,會做一些不同的事情。如果你想匹配這種行爲,那麼在你的代碼中可能會有一些特殊情況。

+0

它推進索引超過替換部分的結尾,我無法弄清楚...... – Chadmmiles

+0

@ user3321382:被替換部分需要多長時間?它從哪裏開始?它在哪裏結束?足夠添加到'index'從它的位置到被替換部分結束的位置。 – user2357112

0

你可以做到以下幾點:

import sys 

def replace_str(string, substring, replace): 
    new_string = '' 
    substr_idx = 0 

    for character in string: 
     if character == substring[substr_idx]: 
      substr_idx += 1 
     else: 
      new_string += character 
     if substr_idx == len(substring): 
      new_string += replace 
      substr_idx = 0 
    return new_string 

if len(sys.argv) != 4: 
    print("Usage: %s [string] [substring] [replace]" % sys.argv[0]) 
    sys.exit(1) 
print(replace_str(sys.argv[1], sys.argv[2], sys.argv[3])) 

請注意,使用清單上的str.join()命令(list.append是O(1))的作品比上面的快,但你說你不能使用字符串方法。

用法示例:

$ python str.py hello ell pa 
hpao 
$ python str.py helloella ell pa 
hpaopaa