11/15, Why does this code work this way?


#1

Hello everyone,

My question doesn’t strictly concern the exercise, but the problem appeared while doing it.
Before I saw the hint with string.split() function, I tried to achieve what this function does by myself.
Along the way I wrote this piece of code:

def censor(text):
  text_list = []
  for character in text:
    index = text.index(character)
    if character == " ":
      text_list.append(text[:index])
  return (text_list)

a = "one two three four"

print censor(a)

I expected this output:

[‘one’, ‘one two’, ‘one two three’]

Instead I got this:

[‘one’, ‘one’, ‘one’]

Could anyone tell me, please, why does this code work this way?
I expected the ‘for’ loop to take every character of a string separately, what happened here instead?

Thank you in advance :slight_smile:


#2

.index() will always find the first match, so the space after the first word.


#3

OK, it makes sense.
Thank you! :slight_smile:


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.