首页 > 解决方案 > Python:TypeError:+的不支持的操作数类型:'NoneType'和'int'

问题描述

我是 Python 的初学者,我在下面的代码中找不到错误。你知道我该如何解决吗?谢谢!

import fileinput
import time
pat = "hello"
cout = 0

with fileinput.input(files=('packet.txt')) as f:
    for line in f:
            start_time = time.time()
            val = search(txt, pat)
            end_time = time.time()
            run_time = (end_time - start_time)*1000000
            if(val == -1):
                print("No Text")
                run_time = (end_time - start_time)*1000000
                #print(" ---> Processing time: "'{0:.3f}'.format(run_time),  "microseconds")
                print(" ---> Processing time: "'{0:.3f}'.format(run_time),  "microseconds")
            else:
                val = val + 1
                print ('Pattern \"' + pat + '\" found at position',val + count)
                run_time = (end_time - start_time)*1000000
                print(" ---> Processing time: "'{0:.3f}'.format(run_time),  "microseconds")

() 中的 TypeError Traceback(最近一次调用最后一次)

     16   print(" ---> Processing time: ",'{0:.3f}'.format(run_time),  "microseconds")
     17             else:
---> 18                     val = val + 1


TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

标签: pythonintnonetype

解决方案


我怀疑您的search()函数None在找不到模式时返回,而不是-1. 所以改变

if val == -1:

if val is None:

推荐阅读