2017-10-12 50 views
0

我試圖創建一個函數來從給定的字符串替換一些值,但我收到以下錯誤:EOL while scanning single-quoted string.功能用於更換和帶鋼

不知道我做錯了:

def DataClean(strToclean): 
     cleanedString = strToclean 
     cleanedString.strip() 
     cleanedString= cleanedString.replace("MMMM/", "").replace("/KKKK" ,"").replace("}","").replace(",","").replace("{","") 
     cleanedString = cleanedString.replace("/TTTT","") 
     if cleanedString[-1:] == "/": 
      cleanedString = cleanedString[:-1] 

     return str(cleanedString) 
+1

您可以分享您提供此功能的數據嗎? – faboolous

+2

請提供輸入到此函數的字符串,以便我們可以測試您正在執行的操作。否則,我們不能幫助。另外,請在產生EOL錯誤的代碼中提供該行。 – TinkerTenorSoftwareGuy

+0

我敢打賭,錯誤不會發生在不包含單引號的函數中。 –

回答

5

您可以通過使用regex模塊更簡單的解決方案來實現該目標。定義一個匹配任何MMM//TTT的模式,並將其替換爲''

import re 

pattern = r'(MMM/)?(/TTT)?' 

text = 'some text MMM/ and /TTT blabla' 
re.sub(pattern, '', text) 
# some text and blabla 

在你的函數它看起來像

import re 

def DataClean(strToclean): 
     clean_str = strToclean.strip() 
     pattern = '(MMM/)?(KKKK)?' 
     new_str = re.sub(pattern, '', text) 
     return str(new_str.rstrip('/')) 

rstrip方法將在字符串的結尾去掉/,如果有任何。 (如果不需要的話)。

使用您在字符串中搜索的所有模式構建模式。使用(pattern)?您將模式定義爲可選。你可以儘可能多地陳述。

它比連接字符串操作更可讀。

注意rstrip方法將移除所有尾隨斜槓,不只是一個。如果你想只刪除最後一個字符,你需要一個if語句:

if new_str[-1] == '/': 
    new_str = new_str[:-1] 

的,如果字符串語句中使用索引訪問,-1表示最後一個字符。分配發生在切片上,直到最後一個字符。

+0

這不是做OP的要求。除了提供替代方案之外,最好幫助OP瞭解他們的代碼有什麼問題。 –

+0

您不需要將輸出封裝到'str'的​​調用中:它已經是一個字符串。另外,'rstrip'將刪除所有*後面的斜槓,而不僅僅是最後一個斜槓。你應該澄清OP的意圖。 –

+0

@MadPhysicist你是對的,我的代碼錯了。我現在修好了 – Vinny