Reputation: 177
I am trying to create a program to generate all possible capitalization cases of a string in python. For example, given 'abcedfghij', I want a program to generate: Abcdefghij ABcdef.. . . aBcdef.. . ABCDEFGHIJ
And so on. I am trying to find a quick way to do it, but I don't know where to start.
Upvotes: 6
Views: 3410
Reputation: 67137
Similar to Dan's solution, but much simpler:
>>> 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']
Upvotes: 10
Reputation: 27216
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))
Out:
abcd Abcd aBcd abCd abcD ABcd AbCd AbcD aBCd aBcD abCD ABCd ABcD AbCD aBCD ABCD
Upvotes: 0
Reputation: 74645
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"))
prints:
['dan', 'daN', 'dAn', 'dAN', 'Dan', 'DaN', 'DAn', 'DAN']
Upvotes: 7