Python Forum

Full Version: string_2, cat,dog
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
count_cat = 0
  count_dog = 0
  for i in range(len(str)-2):
    if str[i:i+3] == 'dog':
      count_dog += 1
    if str[i:i+3] == 'cat':
      count_cat += 1
   
  return count_cat == count_dog
Can someone explain the purpose of the -2 in the for loop?
You need to put your code in code blocks. The text editor here has a button that is the python symbol that will do that for you.

Now onto your question:
range(len(str)-2)
This is the code that's important to understanding your question.
This range produces the indices of all the letters in the string called str, except the last two. The minus two is what prevents the last two characters from being viewed by the for loop
The reason that this is done is shown here:
if str[i:i+3] == 'dog':
str[i:i+3]
is a slice of a string. This means that we are taking all the characters starting at index and ending just before index + 3. In other words the current character plus the next two. If we use this to search the entire string then we must stop the current character 2 characters before the end of the string or will run over the end of the string with our search.
It's not good idea to use str as name.

>>> str(42)
'42'
>>> str = 'oh my god'
>>> str(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
Yes, str is reserved in python. I clipped the code from Gregor Ulm's website.