Python错误:TypeError:需要一个类似字节的对象,而不是'str'

Kay*_*yaP 2 python string input find python-3.x

我正在处理个人项目,但遇到错误: TypeError: a bytes-like object is required, not 'str'

这是我的代码: 单击查看代码

我想制作一个试图在文件中查找输入文本的脚本。谢谢!

小智 6

TypeError implies that there is a mismatch in the datatype required vs given data's type. The function requires input of type 'bytes' while the code inputs data of type 'str'.

To convert the input string into byte-like object use str.encode function.

>>> string = "abcdef"
>>> type(string)
<class 'str'>
>>> string = string.encode('ascii')
>>> type(string)
<class 'bytes'>
Run Code Online (Sandbox Code Playgroud)