我有以下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
产生:
yi yong cheng xu xiang ji yi yong cheng xu xiang
我希望增强此代码,以增加需要大写的连续字符数,直到该数字达到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应该包装,但似乎无法生成优雅的代码(
最佳答案
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
关于python - Python双循环中所有字符串的大写,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7278092/