Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
string_2, cat,dog
#2
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.
Reply


Messages In This Thread
string_2, cat,dog - by Dixon - Dec-20-2019, 10:25 PM
RE: string_2, cat,dog - by Clunk_Head - Dec-20-2019, 11:02 PM
RE: string_2, cat,dog - by perfringo - Dec-21-2019, 12:44 PM
RE: string_2, cat,dog - by Dixon - Dec-21-2019, 05:09 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020