检查是否可以通过在Python中串联list的字符串元素来形成给定的字符串
有时我们需要检查是否可以由列表中存在的许多字符串组成所需的字符串。字符串以什么顺序出现在列表中也没有关系,必须将这些字符串连接起来才能获得所需的字符串。
有排列
从itertools中,我们可以使用permutations函数,该函数将以各种顺序为我们提供列表中字符串的可能组合。一旦给定的组合与所需的字符串匹配,我们就得出可以形成字符串的结论。
示例
from itertools import permutations
chk_str = 'balloon'
Alist = ['fly','on', 'o', 'hot', 'ball', 'air']
def findstring(strchk, biglist):
for i in range(2, len(biglist) + 1):
for perm in permutations(biglist, i):
if ''.join(perm) == strchk:
return True
return False
# Using the function
if(findstring(chk_str,Alist)):
print("可以形成字符串。")
else:
print("字符串无法形成。")输出结果
运行上面的代码给我们以下结果-
可以形成字符串。
带正则表达式
re模块提供了compile函数,该函数将通过指定正则表达式模式来创建可能的字符串。然后将其与要检查的字符串进行比较。如果结果不为空,那么我们可以得出结论,可以形成字符串。
示例
import re
chk_str = 'balloon'
Alist = ['fly','on', 'o', 'hot', 'ball', 'air']
def findstring(strchk, biglist):
r = re.compile("(?:" + "|".join(biglist) + ")*$")
if r.match(strchk) != None:
return True
return False
# Using the function
if(findstring(chk_str,Alist)):
print("可以形成字符串。")
else:
print("字符串无法形成。")输出结果
运行上面的代码给我们以下结果-
可以形成字符串。