Python中双重循环中所有字符字符串的大写化
我有一段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
我想改进这段代码,让它可以连续大写多个字符,直到这个连续的大写字符数量达到字符串长度减去1,这样就能得到:
Abcd aBcd abCd abcD >> - 1 char capitalized
ABcd aBCd abCD AbcD >> - 2 chars capitalized
ABCd aBCD AbCD ABcD >> - 3 chars capitalized
但是当我进行索引运算时,遇到了“索引超出范围”的错误。我知道索引应该是循环的,但就是写不出优雅的代码;(
3 个回答
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
>>>
2
在计算索引号的时候,可以使用取模运算符:
idx = idx % len(str)
顺便提一下,在Python中不要把str
当作变量名。想知道为什么吗?试试这个:
print str(4)
str = 'foo'
print str(4)
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