python - 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'
解决方案
我怀疑您的search()
函数None
在找不到模式时返回,而不是-1
. 所以改变
if val == -1:
至
if val is None:
推荐阅读
- ios - 如何动态更新视图控制器
- android - 如何将 setColorFilter() 与动画一起应用?
- javascript - 检测关闭所有选项卡/关闭导航器上的当前选项卡
- vba - WIndows/VBA:不再识别特殊字符
- c++ - 为什么流写入文件,文件大小每次增加4k?
- python - 联邦学习时的张量类型错误
- angular - 最初调用时可观察到的返回未定义
- javascript - Firebase 分析未显示 Web 应用程序的数据
- swift - 如何在集合视图单元格中禁用 autoresizingmask 约束?
- c++ - C++ 将 HexString 转换为扩展的 Ascii 代码在文本文件中不显示正确的 ascii 代码