2017-03-03 52 views
-1

我有一個長的字符串是這樣的:如何從字符串中移除或翻譯多個字符串?

'[("He tended to be helpful, enthusiastic, and encouraging, even to studentsthat didn\'t have very much innate talent.\\n",), (\'Great instructor\\n\',), (\'He could always say something nice and was always helpful.\\n\',), (\'He knew what he was doing.\\n\',), (\'Likes art\\n\',), (\'He enjoys the classwork.\\n\',), (\'Good discussion of ideas\\n\',), (\'Open-minded\\n\',), (\'We learned stuff without having to take notes, we just applied it to what we were doing; made it an interesting and fun class.\\n\',), (\'Very kind, gave good insight on assignments\\n\',), (\' Really pushed me in what I can do; expanded how I thought about art, the materials used, and how it was visually.\\n\',) 

,我要刪除所有[,(,」,\,\ n在此字符串一次不知爲什麼,我可以通過一個一個做,但始終。以「\ n」失敗了。有沒有什麼有效的辦法可以去除或由於我senectiecs不長,所以我不希望使用字典方法,如前面的問題把所有這些字符或空行符號? 。

+1

可能[Python替換多個str的副本ings](http://stackoverflow.com/questions/6116978/python-replace-multiple-strings) – McGrady

+0

你如何得到這樣的字符串? –

回答

0

也許你可以使用正則表達式來查找您要替換

s = s.strip() 
r = re.compile("\[|\(|\)|\]|\\|\"|'|,") 
s = re.sub(r, '', s) 
print s.replace("\\n", "") 

我有一些問題,與「\人物n「,但在正則表達式之後替換也很容易刪除。

0

如果字符串是正確的Python表達式,然後你可以使用從ast模塊literal_eval轉換字符串元組,然後你可以處理每個元組。

from ast import literal_eval 


' '.join(el[0].strip() for el in literal_eval(your_string)) 

如果沒有,那麼你可以使用這個:

def get_part_string(your_string): 
    for part in re.findall(r'\((.+?)\)', your_string): 
     yield re.sub(r'[\"\'\\\\n]', '', part).strip(', ') 

''.join(get_part_string(your_string)) 
-2

一個解決方案是使用ASCII表值,基本上你只是遍歷字符串,然後如果字符串中的字符是符號[,(,「,\,\ n,你會替換它:

# s is your string 
for i in s: 
if (ord(i) == 91)|(ord(i)==10): 
    s=s.replace(i,'') 

ORD( '[')= 91

ORD( '\ n')= 10

這是不是最好的方法,但它會做的工作。

+0

您的代碼不起作用。你應該修復它或刪除。 –

+0

我編輯它並測試它的工作原理,我剛剛實現了'['和'\ n':>>> s ='[] string \ n with symbols \ n''' >>> for i in s : \t如果(ORD(I)== 91)|(ORD(ⅰ)== 10): \t \t S = s.replace(I, '') >>>小號 「]字符串符號即將被刪除' – distrobyte