CODE CHALLENGE: STRING METHODS Every Other Letter

CODE CHALLENGE: STRING METHODS
Guys, may I ask why in this exercise, even though I define the location of “i” in word must be able to divide 2 without any remainder ==> the output for the second string “Hello World!” is still Hlloworld, in which the second “l” location happens to be word[3], which is not satisfied the if condition?.
Could someone please help me to understand this? Thanks a million times

Every Other Letter
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 .

Write your every_other_letter function here:

def every_other_letter(word):

wordcollection = " "

for i in word:

  if word.find(i) % 2 == 0:

    wordcollection += i

  elif word.find(i) % 2 != 0:

    continue

  elif word == "":

    return wordcollection == ""

return wordcollection

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

ACTUAL OUTPUT
Cdcdm
Hlloworld

Hey Henry!
I don’t understand what you’re asking, however what I know is that whenever you’re doing an operation that requires dividing by 2 with the remainder operator it simply means you either need even numbers (when rest is equal 0) or odd numbers (otherwise).

So in your case why/when do you need any of these conditions to happen?

To use .find() to complete the challenge you would need some extra code, though there are simpler approaches using string slicing.
https://docs.python.org/3/library/stdtypes.html#string-methods

str. find ( sub [, start [, end ]])

Return the lowest index in the string where substring sub is found within the slice s[start:end] . Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

Printing outputs can be very helpful in debugging code, try this:

  for i in word:
    print(i, word.find(i))

A side note: if none of your for loops conditions are satisfied, the loop automatically continues.

Hi @henrynguyen976580333

Welcome to the community!

What you’re doing is rather complicated and as you’ve realized, when a word contains duplicates letter like “Hello world”, it gets ugly because find() by default returns the first occurrence of a character. Hence, like @bavarcarus mentioned, you need to instruct find() with parameters to locate the exact character!

BTW, did you know about indexing with string? Have you explore this or try this?
When “Codecademy” is used:

word = "Codecademy"

print(word[0])
print(word[1])
print(word[2])
print(word[len(word)-1])

Result:

C
o
d
y

You can easily retrieve every other letter by manipulating with the index.

1 Like