If I had a string and a list like this:
myString = "This is a string which has stuff in it."
myList = ["string", "things", "python"]
Is there a way I can remove everything in myString except for the things that are listed in myList (in this case everything is removed except the word 'string')? Any help would be appreciated
myString = "This is a string which has stuff in it."
myList = ["string", "things", "python", "it"]
print([x for x in myList if x in myString])
OUTPUT :
['string', 'it']
import re
myString = "This is a string which has stuff in it."
myList = ["string", "things", "python","it"]
print(" ".join(word for word in re.sub("[^\w]", " ", myString).split() if word in myList))
mytxt = "some sentence to ignore phase and carry on"
reg = re.compile(r"(ignore phase)")
final_str = re.sub(reg,'',mytxt)
print(final_str)
Output -
some word to and carry on
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.