我试图找出字符串中有多少特定关键字,但输出与逻辑不相似
input = raw_input('Enter the statement:') //I love u
keyword = raw_input('Enter the search keyword:') //love
count = 0
for i in input:
if keyword in i:
count = count + 1
print count
print len(input.split())
期待
1
3
现实
0
3
请您参考如下方法:
input 是一个字符串,因此对其进行迭代将分别为您提供每个字符。您可能打算拆分它:
for i in input.split():
请注意,使用列表理解可能比 for 循环更优雅:
count = len([x for x in input.split() if x in keyword])
