Don't understand the concept of this code


#1

Dear sir,
I don’t understand how the process work with this code.

   def count_multi_char_x(word, x):
      splits = word.split(x)
   return(len(splits)-1)

     I don't know why it needs "-1" in ()????

https://www.codecademy.com/courses/pwp-code-challenges/lessons/python-functions-strings-cc/exercises/countx-ii?action=resume_content_item&program_content_id=789d5ad130553ed1b5386ea2de5f1fc3&program_id=0102bb46c9a3ab63ecdc4e00ad667d8f


#2

Did you use the hint or ask for the solution outright?

If you’re unsure why you need the -1, that suggests to me some combination of you don’t fully understand what the split() method does and you’ve either been given that code (as the solution) or arrived at it by trial and error.

When you call split(X) on a string, it breaks your original string into smaller strings using X as the separator. So, let’s say we have word = 'abrakadabra'.

If you were to now call word.split('a'), what Python will do is break up your string into smaller chunks that are delimited by the letter a. So we get:

>>> word.split('a')
['', 'br', 'k', 'd', 'br', '']

We can see that Python has produced a list of 6 items, when we can see that there are only 5 a's in the string. That’s why we need to take 1 away from the length to get the right answer.

Does that help at all?

You can also see the definition of the split() method on the Python docs here:

https://docs.python.org/3/library/stdtypes.html#str.split


#3

Dear sir,

Thank you very much for your explanation. I really get clear answer, thanks a lot.

Best regards,

Tanat

ในวันที่ ส. 15 ก.ย. 2018 18:05 Code Newbro codecademy@discoursemail.com เขียนว่า: