Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Programming - beginner
#1
I am participating in the online course.
Its my first week with limited 1hour/day time for learning so please be understanding.
My question concerns the condition if in the code below. Initially I thought that "if" would concern the length if the string "s" but when I change the value to "if s[:i]" it returns 0 occurences of 'bob'. I simply thought that I would just entered the "s" string length...
Please explain why? What am I missing?

ans=0
s = 'jgguubobxggbobcfybobbob'
for i in range (len(s)):
if s[i:i+3] == 'bob':
ans += 1
print("Number of times bob occurs is: ",ans)
Reply
#2
s[ : i] is a string slice. Because there's no start index, it's from the start of the string, ending at each index in the iteration. Which means it'd only ever match "bob" if "bob" was in the very beginning of the string.

Here's an example:
>>> s = '0123456789'
>>> for i in range(len(s)):
...   print(s[:i])
...

0
01
012
0123
01234
012345
0123456
01234567
012345678
Reply
#3
So, I understand that "if s[i:i+3]" is that s[21:24] ("i" is length of the "s" plus 3) as I simply take the value of "i" which doesnt make sense as it would search for "bob" only between the 23rd letter and the 26th.
I know I am still missing something. Please explain and please advise if I'm asking trivial questions. I need to find out if I'm intelligent enough to learn it.
Reply
#4
(Apr-05-2018, 09:00 PM)dexter7d Wrote: ("i" is length of the "s" plus 3)
That's not what i is. It's each value in the range, so it's a different number every time the for loop runs.
Reply
#5
(Apr-05-2018, 09:03 PM)nilamo Wrote:
(Apr-05-2018, 09:00 PM)dexter7d Wrote: ("i" is length of the "s" plus 3)
That's not what i is. It's each value in the range, so it's a different number every time the for loop runs.
Omg. I got it now. I went on pythontutor to display it and I got it. Thanks. But please say if it was a trivial question :)
Pl
Reply
#6
No question is trivial, until it is :p
Programming is very different from most other things, so for even simple things, it takes time to think about it the right way to make sense.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  beginner programming LED light rbowler 2 34,221 Jun-16-2018, 08:29 PM
Last Post: rbowler

Forum Jump:

User Panel Messages

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