简体   繁体   English

在下一个嵌套列表列表中大写下一个非空元素

[英]capitalize next non-empty element in next list of nested lists

My function aims to take a string as input then output the same string printed the number of times equal to the count of non-empty characters in the string, with the next non-empty element in the next list capitalized. 我的函数的目的是将一个字符串作为输入,然后输出相同的字符串,打印的次数等于字符串中非空字符的数量,下一个列表中的下一个非空元素大写。 The final output should contain the new strings in a list. 最终输出应包含列表中的新字符串。

Example: Input: hello Output: ["Hello", "hEllo", "heLlo", "helLo", "hellO"] 示例:输入: hello输出: ["Hello", "hEllo", "heLlo", "helLo", "hellO"]

Function: 功能:

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

The above function would fulfill all requirements except for capitalizing the next, and only the next letter, in the next string, eg ["Hello", "Hello", "Hello", "Hello", "Hello"] . 上述函数将满足所有要求,除了在下一个字符串中大写下一个字母和下一个字母,例如["Hello", "Hello", "Hello", "Hello", "Hello"] My gut says to count using index slicing, but I'm unsure how to implement without hitting index range errors. 我的直觉说使用索引切片进行计数,但我不确定如何实现而不会遇到索引范围错误。

You can use enumerate() and upper() to get the wanted effect if you iterate over the letters of your word: 如果迭代单词的字母,可以使用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) 

Output: 输出:

['Hello', 'hEllo', 'heLlo', 'helLo', 'hellO']

enumerate() gives you your current position inside the word and you list-slice around to get the right character uppercased. enumerate()为您提供单词内部的当前位置,并列出切片,以获得正确的大写字符。

Related: 有关:

s1 = "hello"

words = []
for i in range(len(s1)):
    words.append(s1[:i] + s1[i:i+1].capitalize() + s1[i+1:])

print(words)

will yield 会屈服

['Hello', 'hEllo', 'heLlo', 'helLo', 'hellO']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM