2

我有以下 Python 代码,循环遍历字符串并将每个字符大写:

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

产生:

Abcd aBcd abCd abcD

我想增强此代码以增加受大写影响的连续字符的数量,直到该数字达到 len(l) - 1 以产生:

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

我在做索引算术时遇到“索引超出范围”错误,理解 idice 应该换行,但似乎无法生成优雅的代码;(

4

3 回答 3

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)

输出:

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
于 2011-09-02T00:39:06.770 回答
2

在计算索引号时使用模运算符:

idx = idx % len(str)

顺便说一句,不要str在 python 中用作变量名。要了解原因,请尝试以下操作:

print str(4)
str = 'foo'
print str(4)
于 2011-09-02T00:33:18.420 回答
2

根据您对 wim 问题的回答,您要么想要wim 的回答,要么想要这个:

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

编辑:当然,如果你想循环这个:

>>> str_ = "abcd"
>>> for x in xrange(1, len(str_) + 1):
...  raise_combinations(str_, x)
... 
Abcd
aBcd
abCd
abcD
ABcd
aBCd
abCD
ABCd
aBCD
ABCD
>>> 
于 2011-09-02T00:51:08.980 回答