Search code examples
pythonlistcapitalization

Capitalization of all characters string in a double loop in Python


I have the following Python code, that cycles thru the string and capitalizes each character:

str = 'abcd'
l  = list(str)
for i in range(len(l)):
    rl = list(str)
    cap_char = l[i].capitalize()
    rl[i] = cap_char
    str1 = ''.join(rl)
    print str1

Which produces:

Abcd aBcd abCd abcD

I would like to enhance this code to increment number of successive characters subject to capitalization until such number reaches len(l) - 1 to produce:

Abcd aBcd abCd abcD    >> - 1 char capitalized
ABcd aBCd abCD AbcD    >> - 2 chars capitalized
ABCd aBCD AbCD ABcD    >> - 3 chars capitalized

I am running into "index out of range" errors when I do index arithmetic, understand idices should wrap, but can't seem to produce an elegant code ;(


Solution

  • import itertools
    x = 'abcd'
    n = len(x)
    for i in xrange(1,n):
      combinations = itertools.combinations(range(n), i)
      for c in combinations:
        print ''.join([k if m not in c else k.upper() for m,k in enumerate(x)]),
      print '    >> - {0} char(s) capitalized'.format(i)
    

    Output:

    Abcd aBcd abCd abcD     >> - 1 char(s) capitalized
    ABcd AbCd AbcD aBCd aBcD abCD     >> - 2 char(s) capitalized
    ABCd ABcD AbCD aBCD     >> - 3 char(s) capitalized