Question:
As per this lesson, we are trying to break apart a word to determine the number of times a sequence of characters is present. One method to solve this is using the .split()
method, which I’ll explain below.
Solution:
If you check the documentation here, we can learn a bit about the .split()
method. First thing to note is that it needs to be applied to strings or variables that are strings.
Next is that it takes two arguments. sep=None , and maxsplit=-1, since both of these have default values this method can be used without any arguments. While I won’t talk about the second parameter here, the first is the separator which is used to define a delimiter that the method can look for. Delimiters are sequences of one or more characters that are used to separate independent regions of text or other data. Outside of this lesson it is great to split each word off from a sentence for example.
In our lesson however we are making use of another advantage of it, that it return
s a list split up by the separator. See below:
'eternity'.split('er')
['et','nity']
'alfalfa'.split('a')
['', 'lf', 'lf', '']
Its important to note based on our second example that a split will always return something on both sides even if it is an ''
empty string. Using this we can see that in each situation, split will return one additional segment on top of the number of times our separator is present in the string. I will leave it to you to determine how that information can solve the lesson.
I hope this explanation helps to understand what’s going on with this method. If you have further questions or wish to discuss this please do so below.