Home>

If an element (string) of the array contains a particular symbol, i am trying to create an array with it removed.

I want to get the following output from an array called result, but it is currently empty.

['a','b','c','d','e']
['a','b','c','&','b--c','a/w','d','s.e','e']
result result
['a','b','c','&','b--c','a/w','d','s.e','e']
candidate
['a','b','c','&','b--c','a/w','d','s.e','e']
result result
[]
Corresponding source code
import re
ans = ['a','b','c','&','b--c','a/w','d','s.e','e']
#reference
candidate = []
#operation
result = []
candidate = ans.copy ()
result = ans.copy ()
print ('candidate')
print (candidate)
print ('result')
print (result)
Since #result is an array that changes elements, prepare candidate as an array that does not change
for i in range (len (candidate)):
    elm = candidate [i]
    if re.search ('--', elm):
        result.remove (elm)
    elif re.search ('/', elm):
        result.remove (elm)
    elif re.search ('.', Elm):
        result.remove (elm)
    elif re.search ('&', elm):
        result.remove (elm)
print ('candidate')
print (candidate)
print ('result')
print (result)
What I tried
<re.Match object;span = (1, 3), match ='-'>

I've checked to see if a match has been determined, but I'm not sure how to change the current code.

import re
ans = ['a','b','c','&','b--c','a/w','d','s.e','e']
#reference
candidate = []
#operation
result = []
candidate = ans.copy ()
result = ans.copy ()
print ('candidate')
print (candidate)
print ('result')
print (result)
Since #result is an array that changes elements, prepare candidate as an array that does not change
for i in range (len (candidate)):
    elm = candidate [i]
    print (re.search ('--', elm))
Supplementary information (FW/tool version, etc.)

Python 3.7.4

  • Answer # 1

    Each string has been deleted in the following places.

    elif re.search ('.', Elm):
            result.remove (elm)


    Let's fix it below.

    elif re.search ('\.', Elm):
            result.remove (elm)

  • Answer # 2

    For your reference, I will present another method.

    ans = ['a','b','c','&','b--c','a/w','d','s.e','e']
    splst = ['--','/','.','&']
    result = [s for s in ans if all (sp not in s for sp in splst)]
    print (result) # ['a','b','c','d','e']

  • Answer # 3

    elif re.search ('.', Elm):

    This is because the "." In the regular expression represents "any single character" in the regular expression.

      elif re.search ('\.', Elm):

    It's a good idea to change it to (\ is a backslash).