2017-03-03 5 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の複写は複数の文字列を置換するings](http://stackoverflow.com/questions/6116978/python-replace-multiple-strings) – McGrady

+0

どのようにこのような文字列を取得しますか? –

答えて

0

をn "しかし、正規表現の後に置き換えるのも簡単です。

0

If文字列が正しいpython式であれば、astモジュールのliteral_evalを使用して文字列をタプルに変換し、その後すべてのタプルを処理できます。

from ast import literal_eval 


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

あなたは、この使用することができない場合:たぶんあなたは、私が「\といくつかの問題を抱えている

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

を交換したいすべての文字を見つけるために正規表現を使用することができ

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

1つの解決策は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 = '[文字列\ n]シンボル\ nを削除する' >>> : \t IF(ORD(I)== 91)|(ORD(I)== 10):記号付き \t \t S = s.replace(I '') >>> S「]ストリング削除される ' – distrobyte

関連する問題