我的函数的目的是将一个字符串作为输入,然后输出相同的字符串,打印的次数等于字符串中非空字符的数量,下一个列表中的下一个非空元素大写。最终输出应包含列表中的新字符串。
示例:输入:hello
输出:["Hello", "hEllo", "heLlo", "helLo", "hellO"]
功能:
def cap_wave(str):
str_split = len([x for x in list(str) if x.isalpha()])
len_list = [list(str) for i in range(1, str_split+1)]
result = []
for i in range(len(len_list)):
temp = []
for t in len_list[i]:
char_modified = t
if not char_modified:
continue
else:
temp.append(char_modified)
result.append(temp)
new_nested = [[a.upper() if i == 0 else a for i, a in enumerate(b)] for b in result]
nest_joins = [''.join(x) for x in new_nested]
return nest_joins
上述函数将满足所有要求,除了将下一个字符串中的下一个字母大写,例如["Hello", "Hello", "Hello", "Hello", "Hello"]
。我的直觉说使用索引切片进行计数,但我不确定如何实现而不会遇到索引范围错误。
如果迭代单词的字母,可以使用enumerate()和upper()来获得想要的效果:
text = "hello" # this will _not_ lowercase first - do that before if you want it
k = []
for i,c in enumerate(text):
k.append(text[:i]+ text[i].upper() + text[i+1:])
print(k)
输出:
['Hello', 'hEllo', 'heLlo', 'helLo', 'hellO']
enumerate()为你提供了你在单词中的当前位置,并且你可以列出切片以获得正确的大写字符。
有关:
s1 = "hello"
words = []
for i in range(len(s1)):
words.append(s1[:i] + s1[i:i+1].capitalize() + s1[i+1:])
print(words)
会屈服
['Hello', 'hEllo', 'heLlo', 'helLo', 'hellO']