检查给定的字符串是否可以通过在 Python 中连接列表的字符串元素来形成

pythonserver side programmingprogramming更新于 2025/12/26 0:12:17

我们有时需要检查所需的字符串是否可以由列表中存在的许多字符串形成。字符串在列表中出现的顺序也无关紧要,必须将它们连接起来才能获得所需的字符串。

使用排列

从 itertools 中,我们可以使用排列函数,它将以各种顺序为我们提供列表中字符串的可能组合。只要给定的组合与所需的字符串匹配,我们就可以得出结论,该字符串可以形成。

示例

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

# 使用函数
if(findstring(chk_str,Alist)):
   print("String can be formed.")
else:
   print("String can not be formed.")

输出

运行上述代码得到以下结果 −

String can be formed.

使用正则表达式

re 模块提供编译函数,该函数将通过指定正则表达式模式来创建可能的字符串。然后将其与要检查的字符串进行比较。如果结果不是无,那么我们可以断定可以形成字符串。

示例

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

# 使用函数
if(findstring(chk_str,Alist)):
   print("String can be formed.")
else:
   print("String can not be formed.")

输出

运行上述代码得到以下结果 −

String can be formed.

相关文章


有用资源