开发者

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, unders开发者_开发技巧tand idices should wrap, but can't seem to produce an elegant code ;(


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


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)


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
>>> 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜