6

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.

peacey
  • 177
  • 1
  • 7
  • 1
    Not sure why the downvotes here? Clear question, even if not a clear reason, many more trivial questions are asked and not downvoted? – agf Jul 19 '11 at 12:54

3 Answers3

10

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']
Ferdinand Beyer
  • 64,979
  • 15
  • 154
  • 145
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"))

prints:

['dan', 'daN', 'dAn', 'dAN', 'Dan', 'DaN', 'DAn', 'DAN']
Dan D.
  • 73,243
  • 15
  • 104
  • 123
  • Thank you. That's working perfectly. I would have never thought to do it this way. I was trying a recursive method and it was taking too long. – peacey Jul 19 '11 at 12:45
  • 4
    You could do this even shorter: `return (''.join(t) for t in product(*zip(s.lower(), s.upper())))`. – Ferdinand Beyer Jul 19 '11 at 12:49
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))

Out:

abcd Abcd aBcd abCd abcD ABcd AbCd AbcD aBCd aBcD abCD ABCd ABcD AbCD aBCD ABCD
utdemir
  • 26,532
  • 10
  • 62
  • 81