-1

I have a long string like this:

 '[("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\',)

and I want to remove all [, (, ", \, \n from this string at once. Somehow I can do it one by one, but always failed with '\n'. Is there any efficient way I can remove or translate all these characters or blank lines symbols? Since my senectiecs are not long so I do not want to use dictionary methods like earlier questions.

MMM
  • 425
  • 1
  • 7
  • 24

2 Answers2

0

If string is correct python expression then you can use literal_eval from ast module to transform string to tuples and after that you can process every tuple.

from ast import literal_eval


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

If not then you can use this:

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))
Greg Eremeev
  • 1,760
  • 5
  • 23
  • 33
0

Maybe you could use regex to find all the characters that you want to replace

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

I have some problems with the "\n" but replacing after the regex is easy to remove too.

Pablo Máximo
  • 467
  • 3
  • 15