这个问题在这里已有答案:
我在python中有一个字符串,我需要找到所有可能的方法,可以选择该字符串的任何子字符串(包括它自己)。子串(为了我的目的)不必在原始字符串中是连续的 - 它可能有间隙。
例如:"frogman"
是这个定义下"froghuman'
的众多子串之一。
例如,will函数:如果我的字符串是"abcd"
,输出应该是:
["a","b","c","d","ab","ac","ad","bc","bd","cd","abc","abd","acd","bcd","abcd"]
您的示例输入/输出表明您正在寻找power set。你可以generate a power set for a string using itertools
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'))))
['',
'a',
'b',
'c',
'd',
'ab',
'ac',
'ad',
'bc',
'bd',
'cd',
'abc',
'abd',
'acd',
'bcd',
'abcd']
注意:输出包含空字符串。