我正在尝试创建一个程序来生成python中字符串的所有可能的大写情况。例如,给定'abcedfghij',我想要一个程序来生成: ABCDEFGHIJ ABCDEF ...... 。 。 ABCDEF ...... 。 ABCDEFGHIJ
等等。我想找到一个快速的方法,但我不知道从哪里开始。
答案 0 :(得分:10)
与Dan的解决方案类似,但更简单:
>>> import itertools
>>> def cc(s):
... return (''.join(t) for t in itertools.product(*zip(s.lower(), s.upper())))
...
>>> print list(cc('dan'))
['dan', 'daN', 'dAn', 'dAN', 'Dan', 'DaN', 'DAn', 'DAN']
答案 1 :(得分:7)
from itertools import product, izip
def Cc(s):
s = s.lower()
for p in product(*[(0,1)]*len(s)):
yield ''.join( c.upper() if t else c for t,c in izip(p,s))
print list(Cc("Dan"))
打印:
['dan', 'daN', 'dAn', 'dAN', 'Dan', 'DaN', 'DAn', 'DAN']
答案 2 :(得分:0)
import itertools
def comb_gen(iterable):
#Generate all combinations of items in iterable
for r in range(len(iterable)+1):
for i in itertools.combinations(iterable, r):
yield i
def upper_by_index(s, indexes):
#return a string which characters specified in indexes is uppered
return "".join(
i.upper() if index in indexes else i
for index, i in enumerate(s)
)
my_string = "abcd"
for i in comb_gen(range(len(my_string))):
print(upper_by_index(my_string, i))
输出:
abcd Abcd aBcd abCd abcD ABcd AbCd AbcD aBCd aBcD abCD ABCd ABcD AbCD aBCD ABCD