在python中查找字符串中所有可能的字母组合

2024-10-01 11:33:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python字符串, 我需要找到所有可能的方法,任何字符串的子串(包括它自己) 可以选择。子字符串(就我的目的而言)在原始字符串中不必是连续的——它可能有间隙。
例如:"frogman"是这个定义下"froghuman'的许多子串之一。在

例如,will函数: 如果我的字符串是"abcd",则输出应该是:

["a","b","c","d","ab","ac","ad","bc","bd","cd","abc","abd","acd","bcd","abcd"]

Tags: 方法函数字符串目的ab定义willad
1条回答
网友
1楼 · 发布于 2024-10-01 11:33:48

您的示例输入/输出表明您正在寻找一个power set。您可以generate a power set for a string using ^{} module in Python

from itertools import chain, combinations

def powerset(iterable):
    "powerset([1,2,3])  > () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

print(list(map(''.join, powerset('abcd'))))

输出

^{pr2}$

注意:输出包括空字符串。在

相关问题 更多 >