【问题标题】:TypeError: cannot concatenate 'str' and 'int' objects 1TypeError:无法连接“str”和“int”对象 1
【发布时间】:2018-03-10 17:22:07
【问题描述】:

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

我在下面写了这个程序。

s = 'azcbobobegghakl'
count = 0
if(s.find("b")):
    p = s.index('b')
    while p+2 <= len(s):
        if(s[p+1] == 'o' and s[p+2] == 'b'):
            count = count+1
            p = s[p+2]
        else:
            p = s[p+1]
print (count)

但它在 while 循环中显示错误。但是如果我不使用 while 循环,它会运行没有任何错误。

【问题讨论】:

    标签: python while-loop typeerror


    【解决方案1】:
    s = 'azcbobobegghakl'
    count = 0
    if(s.find("b")):
        p = s.index('b')
        while p+2 <= len(s):
            if(s[p+1] == 'o' and s[p+2] == 'b'):
                count = count+1
                p = p+2
            else:
                p = p+1
    print (count)
    

    递增 p 时出错。

    我建议为此使用正则表达式。

    【讨论】:

      【解决方案2】:

      试试这个:-

      s = 'azcbobobegghakl'
      count = 0
      result = ''
      ind = 0
      for i in range(3,len(s),3):
          result += s[ind:i]
          if "bob" in result:
              count+=1
          ind = i
          result = s[i-1]
      print(count)
      

      【讨论】:

        猜你喜欢
        • 2011-10-23
        • 1970-01-01
        • 1970-01-01
        • 2015-09-01
        • 2020-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-01
        相关资源
        最近更新 更多