找出单词“ dog”是否在字符串中。
我尝试执行此代码,但我不知道错误在哪里。
y='dogaway'
for i in range(len(y)):
if y[i:i+2]=='dog':
x=x+1
print(x)
我希望输出为1,但实际输出为0。
答案 0 :(得分:1)
更简单:
if 'dog' in y:
...
答案 1 :(得分:1)
您可以使用count
。
y = 'dogaway'
print(y.count('dog')) # Outputs 1
或者,如果您想修改代码,那么您的接头就差一点了:
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)
答案 2 :(得分:-1)
您可以在Python中使用in
成员资格运算符。
'dog' in 'dogaway'
返回True