Is there a way to remove multiple strings from a single string in list inclusion?

Asked 2 years ago, Updated 2 years ago, 32 views

The summary of my question is how to write the action of removing more than one unwanted string from a string in a list notation.

For example,

 "a Everyone a, b, b, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c

Remove unnecessary ["a", "b", "c", and "NULL" from the

"Thank you for your cooperation."

to obtain
words="a, everyone a, b, b, c, c, please, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL.
alist=["a", "b", "c", "NULL"]
for delstrin alist:
    words=words.replace(delstr, "")

It is processed as follows.However, there are many words and the alist is huge, so I thought it would be possible to speed up the list, so I wrote the following code.

 [words.replace(delstr, "") for delstrin alist]

However, this does not serve the purpose because it gives you a list of each element of the alist removed from words.

One method is to remove the alist element from the list of words per loop with the words listed above, but if the list of words and the list can be included in a single object, it is more desirable.I would appreciate it if you could let me know if there is a way to remove all the elements of alist from words by listing.

python

2022-09-30 20:23

2 Answers

This proposal uses re.sub.

import re
words_re=re.compile("|".join(re.escape(w)for win list))
result=re.sub(words_re, '', words)

Please note that depending on the contents of the deleted string (alist), the result will be different from repeating replace.For example,

words="<abc>"
alist=["b", "abc" ]

If so, replace only deletes b and the result is <ac>, and the regular expression starts matching abc first, so abc is deleted and the result is <.


2022-09-30 20:23

You can write in one line using the high-level function functools.reduce.
https://docs.python.org/ja/3/howto/functional.html#the-functools-module

def func(a,b):
  return a.replace(b, "")

words="a, everyone a, b, b, c, please c, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL.
alist=["a", "b", "c", "NULL"]
functools.reduce(func,alist,words)

If you write this using the lambda formula,

 functools.reduce(lambdaa, b:a.replace(b, "", alist, words)

However, the document says, "In many cases, it is easier to simply write a for loop than using functools.reduce()."


2022-09-30 20:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.