-1

Find out if word 'dog' is in a string.

I tried doing this code and i dont know where the error is .

y='dogaway'
for i in range(len(y)):
    if y[i:i+2]=='dog':
        x=x+1
print(x)

I expected output to be 1 but the actual ouput is 0.

3 Answers3

1

You can use count.

y = 'dogaway'
print(y.count('dog')) # Outputs 1

or if you want to fix your code, you are just off by one in your splice:

y = 'dogaway'
x = 0
for i in range(len(y) - 3): # Make sure your range accounts for the look ahead
    # In the future add a print to make sure it is doing what you expect:
    # print(y[i:i + 2])
    if y[i:i + 3] == 'dog': # Here you were off by 1
        x = x + 1
print(x)
0

Even simpler:

if 'dog' in y:
    ...
nKn
  • 13,691
  • 9
  • 45
  • 62
  • 3
    This doesn't give the expected output. – Sayse Jun 21 '19 at 13:02
  • As I see your comment is being upvoted, I refer to the same comment on the other answer: You don't know if this is the expected output, as the "1" might only be a flag to check if the containing code is or not working. This *does* what the OP is asking: "Find out if word 'dog' is in a string." – nKn Jun 21 '19 at 13:48
-2

You can use the in membership operator in Python.

'dog' in 'dogaway'

returns True

Felipe Sulser
  • 1,185
  • 8
  • 19
  • 1
    This doesn't give the expected output. – Sayse Jun 21 '19 at 13:02
  • 2
    He wants to find out if the word dog is in the string I don't the think 1 is that important –  Jun 21 '19 at 13:03
  • 1
    If what you want is 0 or 1 just do `int('dog' in 'dogaway')` – Felipe Sulser Jun 21 '19 at 13:04
  • @JonathanDyke - From the given information, that is impossible to know why it is the expected output and what they intend to do with it – Sayse Jun 21 '19 at 13:07
  • 1
    @Sayse then how do you know it's not the expected output? – nKn Jun 21 '19 at 13:09
  • "I expected output to be 1" is pretty explicit – Sayse Jun 21 '19 at 13:10
  • It doesn't mean he wants to do anything with that "1", maybe he's just a Python newbie and is trying to do basic operations. The first sentence is pretty explicit as well ("Find out if word 'dog' is in a string."). – nKn Jun 21 '19 at 13:12
  • 2
    The question is: How to find a letter in a string in Python. Does the provided answer not bring a solution to that? – Felipe Sulser Jun 21 '19 at 13:13