📌  相关文章
📜  Python - 删除带有任何非必需字符的字符串

📅  最后修改于: 2022-05-13 01:54:51.623000             🧑  作者: Mango

Python - 删除带有任何非必需字符的字符串

给定一个字符串列表,删除字符串,如果它包含任何不需要的字符。

方法 #1:使用列表理解+ any()

在此,我们测试所有字符串并使用 any() 迭代所有非必需字符列表并检查其在字符串中的存在,如果找到,则该列表不包含在结果列表中。

Python3
# Python3 code to demonstrate working of
# Remove strings with any non-required character
# Using list comprehension + any()
  
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# non-required char list
chr_list = ['f', 'm', 'n', 'i']
  
# checking for all strings
# removing if contains even 1 character
res = [sub for sub in test_list if not any(ele in sub for ele in chr_list)]
  
# printing result
print("Filtered Strings : " + str(res))


Python3
# Python3 code to demonstrate working of
# Remove strings with any non-required character
# Using filter() + lambda + any()
  
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# non-required char list
chr_list = ['f', 'm', 'n', 'i']
  
# checking for all strings
# filter and lambda used to do this task
res = list(filter(lambda sub: not any(
    ele in sub for ele in chr_list), test_list))
  
# printing result
print("Filtered Strings : " + str(res))


输出
The original list is : ['gfg', 'is', 'best', 'for', 'geeks']
Filtered Strings : ['best', 'geeks']

方法 #2:使用 filter() + lambda + any()

在这里,我们使用 filter() 和 lambda函数执行过滤任务。 Rest any() 用于检查字符串中是否存在任何字符以将其删除。

蟒蛇3

# Python3 code to demonstrate working of
# Remove strings with any non-required character
# Using filter() + lambda + any()
  
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# non-required char list
chr_list = ['f', 'm', 'n', 'i']
  
# checking for all strings
# filter and lambda used to do this task
res = list(filter(lambda sub: not any(
    ele in sub for ele in chr_list), test_list))
  
# printing result
print("Filtered Strings : " + str(res))
输出
The original list is : ['gfg', 'is', 'best', 'for', 'geeks']
Filtered Strings : ['best', 'geeks']