Skip to content
Advertisement

How to make enumerate not count blank’s indexes?

I am trying to writing a function which will take a sentence and make each odd letter an uppercase one and each even letter a lowercase one.

Here is what I tried:

def func(st):
    res = []
    for index, c in enumerate(st):
        if index % 2 == 0:
            res.append(c.upper())
        else:
            res.append(c.lower())
    return ''.join(res)
print(myfunc(something))

When the input is "Hello my guy", the output is "HeLlO My gUy" and not "HeLlO mY gUy" because it counts blank as a letter, what can I do?

Advertisement

Answer

I’d write it like this:

from itertools import cycle

def my_func(st):
    operation = cycle((str.upper, str.lower))
    conv = [next(operation)(c) if c != ' ' else c for c in st]
    return ''.join(conv)

Demo:

>>> my_func("Hello my guy")
'HeLlO mY gUy'
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement