如何在字符串中生成所有3个大写的组合? 例如:
f("abcde") => ['ABCde', 'aBCDe', 'abCDE', 'ABcDe', 'ABcdE' ...]
答案 0 :(得分:3)
一种方法是生成字母的笛卡尔积(以小写和大写两种形式),然后只保留3个大写字母
from itertools import product
def combs(s, n):
pairs = tuple(i.lower() + i.upper() for i in s)
for i in product(*pairs):
if sum(1 for j in i if j.isupper()) == n:
yield ''.join(i)
实施例
for s in combs('abcde', 3):
print(s)
输出
abCDE
aBcDE
aBCdE
aBCDe
AbcDE
AbCdE
AbCDe
ABcdE
ABcDe
ABCde
答案 1 :(得分:1)
def f(s):
r = []
for i in range(1, len(s)-1):
for j in range(i+1, len(s)):
r.append(s[:i].capitalize() + s[i:j].capitalize() + s[j:].capitalize())
return r