Traceback (most recent call last): File "C:\Users\LX\Desktop\00.py", line 9, in <module> match = re.search(pattern, text, start_pos) File "C:\Users\LX\AppData\Local\Programs\Python\Python310\lib\re.py", line 200, in search return _compile(pattern, flags).search(string) TypeError: cannot use a bytes pattern on a string-like object 这是报错,你再看一下
时间: 2023-07-22 07:09:51 浏览: 62
根据错误信息,报错是因为尝试在字符串对象上使用字节模式。在 Python 中,`re.search()` 函数要求模式和字符串对象的类型匹配。
解决这个问题的方法是将字符串对象转换为字节对象,以便与字节模式匹配。
请尝试将 `text` 变量从字符串类型转换为字节类型,如下所示:
```python
import re
text = b"Hello, Hello, Hello!" # 将字符串对象转换为字节对象
pattern = b"Hello" # 字节模式
# 使用 re.search() 函数匹配多个位置
start_pos = 0
while True:
match = re.search(pattern, text, start_pos)
if match:
start_pos = match.end()
print(f"Found at position {match.start()} - {match.end()}")
else:
break
```
在上述代码中,我们将 `text` 变量的类型更改为字节类型,即 `b"Hello, Hello, Hello!"`。这样就可以避免在字节模式上使用字符串对象的错误,并且能够正常运行 `re.search()` 函数来匹配多个位置。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![iso](https://img-home.csdnimg.cn/images/20210720083646.png)