我有以下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
当我进行索引算法时,我遇到“索引超出范围”错误,理解idices应该换行,但似乎无法产生优雅的代码;(
答案 0 :(得分: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
答案 1 :(得分:2)
在计算索引号时使用模运算符:
idx = idx % len(str)
顺便说一句,不要在python中使用str
作为可变名称。要了解原因,请尝试以下方法:
print str(4)
str = 'foo'
print str(4)
答案 2 :(得分:2)
根据您对wim问题的回答,您要么wim's answer要么:
>>> 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
>>>