繁体   English   中英

有什么方法可以替换/删除字符串中除某些短语以外的所有内容?

[英]Is there a way I can replace/remove everything in a string except for certain phrases?

如果我有一个字符串和像这样的列表:

myString = "This is a string which has stuff in it."
myList = ["string", "things", "python"]

有什么方法可以删除myString中除myList中列出的内容以外的所有内容(在这种情况下,除单词'string'以外的所有内容均已删除)? 任何帮助,将不胜感激

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])

输出

['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)

输出-

一些话要继续

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM