Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

|PYTHON|BEGINNER| This code isnt working for the last 4 or 5 indexes of the string. Why?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Output
'aNtHrOpOmOrpHIsm'

Expected Output:
'aNtHrOpOmOrPhIsM'

Any ideas why it doesnt work?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading