-1
import re
a = ["%!It depends%% on what you m\\ean by dying.",
     "It is widely~ read and at the top_x000D_ of all the search%%__ engines.",
     "\\H~owever, Wikipedia has internal problems",
     "%%a+b!=a-b"]
p = [((((((str(a[i]).replace("%!", "")).replace("%", ""))
     .replace("~", "")).replace("_x000D_","")).replace("__", ""))
     .replace("\\", "")) for i in range(len(a)) if a[i] != ""]
print(p)
Jan
  • 42,290
  • 8
  • 54
  • 79
Gagan
  • 11
  • 4
  • 1
    Note that you can directly chain ``.replace`` calls, as in ``str(a[i]).replace("%!", "").replace("%", "")`` and so on. There is no need to wrap intermediate results in parentheses. – MisterMiyagi May 18 '20 at 09:12
  • Have a look at https://stackoverflow.com/questions/3136689/find-and-replace-string-values-in-list – JGK May 18 '20 at 09:13
  • Also [How to replace multiple substrings of a string?](https://stackoverflow.com/questions/6116978/how-to-replace-multiple-substrings-of-a-string) – user2314737 May 18 '20 at 09:14

3 Answers3

1

Yes you can use re.sub instead

p2 = [re.sub(r"%!|%|~|_x000D_|__|\\", "", str(a[i])) for i in range(len(a)) if a[i] != ""]

For more info read the documentation here: https://docs.python.org/3/library/re.html#re.sub

Pani
  • 1,317
  • 1
  • 14
  • 20
0

Since you import re package, I think you want to do this in regular expression way.

to_replace = ['%!', '%', '~', '_x000D_', '__', '\\']
to_replace = ")|(".join(map(re.escape, to_replace))
p = [re.sub(f'({to_replace})', '', a[i]) for i in range(len(a)) if a[i] != '']

It's recommend to use re.escape to avoid invalid symbol in regexp.

PenutChen
  • 193
  • 8
0

You could use

import re
a = ["%!It depends%% on what you m\\ean by dying.",
     "It is widely~ read and at the top_x000D_ of all the search%%__ engines.",
     "\\H~owever, Wikipedia has internal problems",
     "%%a+b!=a-b"]
pattern = re.compile(r'%!|_x000D_|__|[~%\\]')
p = [pattern.sub('', item) for item in a if item]
print(p)

Which yields

['It depends on what you mean by dying.', 
 'It is widely read and at the top of all the search engines.',
 'However, Wikipedia has internal problems', 
 'a+b!=a-b']

Remember to put the longer substitutions left of the alternation.

Jan
  • 42,290
  • 8
  • 54
  • 79