Don't understand the concept of this code


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

   def count_multi_char_x(word, x):
      splits = word.split(x)

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


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:


Dear sir,

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

Best regards,


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


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