1

I have a search string If the character inside the search matches then replace with None

sear = '!%'
special_characters = ['!', '"', '#', '$', '%','(',')']
for remove_char in special_characters:
   search_value = re.sub(remove_char, '', sear)

My out got error

Expected out is None

sear = 'ABC!%DEF'
Expected is 'ABCDEF'
sear = 'ABC,DEF'
Expected is 'ABC,DEF'

2 Answers2

6

Just do a list comprehension and ''.join:

sear = '!%'
special_characters = ['!', '"', '#', '$', '%']
sear = ''.join([i for i in sear if i not in special_characters])
print(sear)

This code iterates the string by characters, and see if the character is not in the special_characters list, if it's not, it keeps it, if it is, it removes, but that only gives us a list of strings, so we need ''.join to change it into a string.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
2

You can make a regex character class out of your special characters and then use a regex substitution to do the replacements. For longer strings or larger lists of special characters, you should find this runs 2-3x faster than the list comprehension solution.

import re

special_characters = ['!', '"', '#', '$', '%','(',')']
regex = re.compile('[' + ''.join(f'\{c}' for c in special_characters) + ']')

sear = '!%'
search_value = regex.sub('', sear)
print(search_value)
sear = 'ABC!%DEF'
search_value = regex.sub('', sear)
print(search_value)
sear = 'ABC,DEF'
search_value = regex.sub('', sear)
print(search_value)

Output:

<blank line>
ABCDEF
ABC,DEF

Note I've prefixed all characters in the character class with \ so that you don't have to worry about using characters such as - and ] which have special meaning within a character class.

Nick
  • 138,499
  • 22
  • 57
  • 95