📜  Python|获取字符串中匹配的子字符串

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

Python|获取字符串中匹配的子字符串

字符串中单个子字符串的测试已经讨论过很多次了。但有时,我们有一个潜在子字符串的列表,并检查哪些子字符串出现在目标字符串中作为子字符串。让我们讨论可以执行此任务的某些方式。

方法#1:使用列表推导
使用列表理解是执行此特定任务的天真和蛮力方法。在此方法中,我们尝试使用“in”运算符获取匹配的字符串并将其存储在新列表中。

# Python3 code to demonstrate working of
# Get matching substrings in string
# Using list comprehension
  
# initializing string 
test_str = "GfG is good website"
  
# initializing potential substrings
test_list = ["GfG", "site", "CS", "Geeks", "Tutorial" ]
  
# printing original string 
print("The original string is : " + test_str)
  
# printing potential strings list
print("The original list is : " + str(test_list))
  
# using list comprehension
# Get matching substrings in string
res = [sub for sub in test_list if sub in test_str]
  
# printing result 
print("The list of found substrings : " + str(res))
输出 :
The original string is : GfG is good website
The original list is : ['GfG', 'site', 'CS', 'Geeks', 'Tutorial']
The list of found substrings : ['GfG', 'site']

方法 #2:使用filter() + lambda
此任务也可以使用 filter函数执行,该函数执行过滤掉使用 lambda函数检查是否存在的结果字符串的任务。

# Python3 code to demonstrate working of
# Get matching substrings in string
# Using lambda and filter()
  
# initializing string 
test_str = "GfG is good website"
  
# initializing potential substrings
test_list = ["GfG", "site", "CS", "Geeks", "Tutorial" ]
  
# printing original string 
print("The original string is : " + test_str)
  
# printing potential strings list
print("The original list is : " + str(test_list))
  
# using lambda and filter()
# Get matching substrings in string
res = list(filter(lambda x:  x in test_str, test_list))
  
# printing result 
print("The list of found substrings : " + str(res))
输出 :
The original string is : GfG is good website
The original list is : ['GfG', 'site', 'CS', 'Geeks', 'Tutorial']
The list of found substrings : ['GfG', 'site']