2016-02-08 1156 views
3

任務是將任何字符串轉換爲任何沒有內置的字符串.replace()。我失敗了,因爲我忘記了技術上的空間也是一個字符串。首先,我將這個字符串轉換爲列表,但現在我發現我做了不必要的事情。但是,它仍然不起作用。Python - 無需替換多個字符.replace()

  1. 我可以取代「貓」變成了「狗」
  2. 我可以代替「C」到「狗」

我不能取代「貓」變成了「一隻狗」。

我試過lambdazip,但我真的不知道該怎麼做。你有任何線索嗎?

string = "Alice has a cat, a cat has Alice." 
old = "a cat" 
new = "a dog" 

def rplstr(string,old,new): 
    """ docstring""" 

    result = '' 
    for i in string: 
     if i == old: 
      i = new 
     result += i 
    return result 

print rplstr(string, old, new) 
+2

你試過're.sub'嗎? –

+0

嗯......給定的字符串是不可變的,真的這個任務沒有意義,因爲你可以只是'返回新的'... – Claudiu

回答

2

您可以通過串腳印,一次一個字符,並測試,看它是否與您的old字符串的第一個字符相匹配。如果匹配,請保留對索引的引用,然後繼續遍歷字符,現在嘗試匹配old的第二個字符。繼續前進,直到匹配整個old字符串。如果完全匹配成功,則使用第一個字符匹配的索引和old字符串的長度創建一個插入new字符串的新字符串。

def replstr(orig, old, new): 
    i = 0 
    output = '' 
    temp = '' 
    for c in orig: 
     if c == old[i]: 
      i += 1 
      temp += c 
     else: 
      i = 0 
      if temp: 
       output += temp 
       temp = '' 
      output += c 
     if len(temp) == len(old): 
      output += new 
      temp = '' 
      i = 0 
    else: 
     if temp: 
      output += temp 
+0

>>>愛麗絲hasa狗,哈哈aAalaiacaea.a 這就是我所擁有的,但可能只是代碼中的一些小事情的問題。一隻貓變成了一隻狗。我會幾次讀你的代碼。謝謝。 –

+0

@TomWojcik啊,是的,我錯過了一條線。更新。 –

1

你可以用切片做到這一點:

def rplstr(string, old, new): 
    for i in xrange(len(string)): 
     if old == string[i:i+len(old)]: 
      string = string[:i] + new + string[i+len(old):] 
    return string 
+1

我相信如果'new'字符串比'old'字符串長,那麼字符串末尾的字母將不會被測試。或者如果'new'字符串包含'old'字符串。 –

+0

先生,您知道如何編碼。謝謝。完美的作品,它相對簡單。 –

3

該解決方案避免了字符串連接可以是低效率的。它創建段的名單在最後聯合起來:

string = "Alice has a cat, a cat has Alice." 
old = "a cat" 
new = "a dog" 

def rplstr(string, old, new): 
    """ docstring""" 

    output = [] 
    index = 0 

    while True: 
     next = string.find(old, index) 

     if next == -1: 
      output.append(string[index:]) 
      return ''.join(output) 
     else: 
      output.append(string[index:next]) 
      output.append(new) 
      index = next + len(old) 

print rplstr(string, old, new) 

,並提供:

Alice has a dog, a dog has Alice. 
+0

很漂亮。 –

2

您可以通過使用正則表達式做一個簡單的小方法。

import re 

my_string = "Alice has a cat, a cat has Alice." 
new_string = re.sub(r'a cat', 'a dog', my_string) 
print new_string 
+0

事實上,它確實有效,但我的導師說我們不能使用任何內置方法,也不能使用正則表達式。 –