Coding Question 2 - Every Other Letter: Link to coding question
Create a function named every_other_letter that takes a string named word as a parameter. The function should return a string containing every other letter in word .
I’m trying to solve the question above with the code shown below. For the first example, it works and provides the correct output. However, I am having trouble figuring out why the second test is outputting “Hllool!”.
def every_other_letter(word):
new_word = ""
joined_word = ''.join(word.split())
for i in joined_word:
if joined_word.index(i) % 2 == 0:
new_word += i
return new_word
# Uncomment these function calls to test your function:
print(every_other_letter("Codecademy"))
# should print Cdcdm
print(every_other_letter("Hello world!"))
# should print Hlowrd
print(every_other_letter(""))
# should print
I see an issue here: if joined_word.index(i) % 2 == 0:
you have for i in joined_word:
which iterated through each character of the string, one by one
first h, then e, then l, then l, then o, and so on.
But .index always finds the first index where that something is found.
So for the second l, i is l, and joined_word.index('l') would always be 2, since the first l is at index 2 in that list.
so joined_word.index(i) % 2 is 0
so joined_word.index(i) % 2 == 0 is True
so that l is added to the new_word string.
I recommend iterating using the indices instead of what’s in the string or list to get around this problem.
def every_other_letter(word):
new_word = ""
for i in range(0, len(word)):
if i % 2 == 0:
new_word += word[i]
return new_word
# Uncomment these function calls to test your function:
print(every_other_letter("Codecademy"))
# should print Cdcdm
print(every_other_letter("Hello world!"))
# should print Hlowrd
print(every_other_letter(""))
# should print