Home > Software engineering >  How to make enumerate not count blank's indexes?
How to make enumerate not count blank's indexes?

Time:06-24

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 my_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(my_func(Sentence))

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?

CodePudding user response:

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'

CodePudding user response:

You can use a separate index variable to count letters as follows:

def my_func(st):
    res = []
    i = 1
    for j in st:
        if j != " ":
            if i%2 == 0:
                res.append(j.lower())
            else:
                res.append(j.upper())
            i  = 1
        else:
            res.append(" ")
    return ''.join(res)
print(my_func("Hello my guy"))

Output:

HeLlO mY gUy

CodePudding user response:

def my_func(st):
    res = []
    index = 0
    for c in st:
        res.append(c.upper() if index%2==0 else c.lower())
        if c != " ":
            index  = 1
    return ''.join(res)
Sentence = "Hello my guy"
print(my_func(Sentence))  # HeLlO mY gUy

enumerate() method adds counter to an iterable and returns it. It seems easier to count the index you need directly than to use the index returned by the enumerate.

CodePudding user response:

While I strongly recommend @timgeb's approach, here is another look at this:

import itertools

def my_func(st):
    
    st_double = st.replace(" ", "  ")
    return "".join(itertools.chain.from_iterable(
                    zip(map(str.upper, st_double[::2]), st_double[1::2]))
                  ).replace("  ", " ")

my_func("Hello my guy")
'HeLlO mY gUy'

Use indexing to split the string into even and odd, apply str.upper to even, and zip back together. Spaces are being taken care of by doubling them first.

CodePudding user response:

See another solution using while loop:

Sentence = "hello my guy stack test"
def my_func(st):
    res = []
    counter = 0
    j = 0
    while counter < len(st):
        if st[counter] == ' ':
            res.append(st[counter])
        else:
            if j%2 == 0:
                res.append(st[counter].upper())
            else:
                res.append(st[counter].lower())
            j  =1
        counter  =1
    return ''.join(res)

print(my_func(Sentence))

See the output as:

enter image description here

  • Related