Home > Back-end >  |PYTHON|BEGINNER| This code isnt working for the last 4 or 5 indexes of the string. Why?
|PYTHON|BEGINNER| This code isnt working for the last 4 or 5 indexes of the string. Why?

Time:07-04

The purpose of this code is to make the odd placed letters uppercase and the odd ones lower cased, I've tried about everything I can think of and it doesnt work.


def myfunc(word):
    new_word = ''
    for let in word:
        if (word.index(let)   1) % 2 == 0:
            new_word  = let.upper()
        elif (word.index(let)   1) % 2 == 1:
            new_word  = let.lower()
            
    return new_word

The code works fine for the first few but when it gets towards the end it looses its brain cells.

Input myfunc('Anthropomorphism')

Output 'aNtHrOpOmOrpHIsm'

Expected Output: 'aNtHrOpOmOrPhIsM'

Any ideas why it doesnt work?

CodePudding user response:

word.index(let) will get you the first index of that letter, not the current one as you iterate. Use for index, letter in enumerate(word): instead.

def myfunc(word):
    new_word = ''
    for index, let in enumerate(word):
        if (index   1) % 2 == 0:
            new_word  = let.upper()
        elif (index   1) % 2 == 1:
            new_word  = let.lower()
            
    return new_word

or slightly more concise:

def myfunc(word):
    new_word = ''
    for index, let in enumerate(word):
        new_word  = let.upper() if index % 2 else let.lower()
    return new_word

and even a pythonic 1-liner:

def myfunc(word):
    return ''.join(let.upper() if index % 2 else let.lower() for index, let in enumerate(word))
  • Related