1

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"]

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"]. My gut says to count using index slicing, but I'm unsure how to implement without hitting index range errors.

Mr. Jibz
  • 511
  • 2
  • 7
  • 21

2 Answers2

2

You can use enumerate() and upper() to get the wanted effect if you iterate over the letters of your word:

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.

Related:

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
1
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']
andreihondrari
  • 5,743
  • 5
  • 30
  • 59