I am trying to write a function that would pull every other letter of any given word. Can someone please explain why this code does not produce every other letter?
def other_letter(word):
other_letter = ""
for letter in word:
if word.index(letter) % 2 == 0:
other_letter = letter
return other_letter
print(other_letter("Hello World!"))
I thought that if modulo of whatever the index is equal to 0 then it should pull every other letter and add it to the other_letter
? I found another way to solve this issue, without modulo operator, but I am wondering why modulo operator didn't work here?
CodePudding user response:
The problem you are facing is that in your code, you are checking the index of the letter in the word. This means it finds the first instance of the letter and not the current instance.
I.e. "l"
is always index 2
, "o"
is always index 4
, so all the l's and o's will appear in your resulting string, instead of just the first "l"
and first "o"
.
To iterate over an Iterable while keeping track of the index, you can use enumerate
to generate an Iterable of index, value pairs. But in this case it's still not the most concise solution.
A simpler solution would be to use the skip parameter to the brackets operator.
When using []
on a sequence including a string, the first parameter is the start index, the second is the end index (one after the last element), and the third is the skip amount.
If you leave out the start and end indices, you simply iterate over the entire string, and you can still apply the skip parameter to skip over certain amounts of letters.
def other_letter(word: str):
"""Return a string of every other letter in word."""
return word[::2]
Example:
>>> word = "Hello World!"
>>> print(word[::2])
'HloWrd'
If you want to start from the second letter, you can use the start index as 1 instead of the default 0:
>>> print(word[1::2])
'el ol!'
CodePudding user response:
.index()
will return the index of the first occurrence of that letter, so if your string has more than one of the same letter, your method won't work.
Try using enumerate
to get the actual index of the letter:
for index, letter in enumerate(word):
if index % 2 == 0:
other_letter = letter