Beginner
Beginner

Reputation: 31

Why doesn't this work for the last 4 or 5 indexes of the string?

The purpose of this code is to make the odd placed letters uppercase and the odd ones lowercase.

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

It works fine for the first few but when it gets towards the end it loses its brain cells.

Input: myfunc('Anthropomorphism')

Output: 'aNtHrOpOmOrpHIsm'

Expected Output: 'aNtHrOpOmOrPhIsM'

Any ideas why it doesn't work?

Upvotes: 0

Views: 141

Answers (1)

Julien
Julien

Reputation: 15206

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))

Upvotes: 2

Related Questions