2

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 ;(

begemot
  • 23
  • 3

3 Answers3

3
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
wim
  • 338,267
  • 99
  • 616
  • 750
2

use modulo operator while computing index number:

idx = idx % len(str)

BTW, do not use str as a varaible name in python. To understand why, try this:

print str(4)
str = 'foo'
print str(4)
Michał Šrajer
  • 30,364
  • 7
  • 62
  • 85
2

Depending on your answer to wim's question, you either want wim's answer or this:

>>> def upper_case(str_, start, end):
...  substr = str_[start:end].upper()
...  return str_[:start] + substr + str_[end:]
... 
>>> def raise_combinations(str_, length):
...  for x in xrange(len(str_) - length + 1):
...   print(upper_case(str_, x, x + length))
... 
>>> raise_combinations('abcdefghi', 1)
Abcdefghi
aBcdefghi
abCdefghi
abcDefghi
abcdEfghi
abcdeFghi
abcdefGhi
abcdefgHi
abcdefghI
>>> raise_combinations('abcdefghi', 4)
ABCDefghi
aBCDEfghi
abCDEFghi
abcDEFGhi
abcdEFGHi
abcdeFGHI

EDIT: And, of course, if you want to loop over this:

>>> str_ = "abcd"
>>> for x in xrange(1, len(str_) + 1):
...  raise_combinations(str_, x)
... 
Abcd
aBcd
abCd
abcD
ABcd
aBCd
abCD
ABCd
aBCD
ABCD
>>> 
Community
  • 1
  • 1
Umang
  • 5,196
  • 2
  • 25
  • 24