Reputation: 31
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
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