【问题标题】:couting a set of word in python在python中计算一组单词
【发布时间】:2018-01-22 16:33:00
【问题描述】:

假设 s 是一串小写字符。

编写一个程序,打印字符串 'bob' 在 s 中出现的次数。例如,如果 s = 'azcbobobegghakl',那么你的程序应该打印

bob出现的次数是:2

这是我的答案,但我不知道我的代码有什么问题。请帮忙

s = "azcbobobegghakl"
coutBob=0
i=0
for char in range (len(s)):
    if char[i:i+3]=="bob":
        coutBob+=1
    else:
        i=i+1
print ("Number of times bob occurs is: " + str(coutBob))

【问题讨论】:

标签: python-3.x


【解决方案1】:

你需要下标字符串s,而不是索引:

for i in range(len(s)):
    if s[i:i+3]=="bob":
        coutBob+=1

【讨论】:

    【解决方案2】:

    我想这会对你有所帮助。

    b = list(s)
    i = 0
    j = 0
    for i in range(0,len(b)-2):
        if b[i]=='b' and b[i+1]=='o' and b[i+2]=='b':
           j = j + 1
    print ("Number of times bob occurs is: %d"%j)
    

    【讨论】:

      猜你喜欢
      • 2015-06-14
      • 2012-08-07
      • 2015-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多