python - 对元组使用 re.match() 的“预期字符串或类似字节的对象”
问题描述
如果有人可以提供帮助,我希望我所在的地区没有任何人在编码!
我正在使用 vs 代码
import re
data = ('bat', 'bit', 'but','gdt', 'hat', 'hit', 'hut', 'hdg', 'grt')
patt = (r'[bh][aiu]t')
res = re.match('patt', data)
res.group()
res.groups()
我需要将模式匹配到 bat,bet,bit,hut。但是,我收到这些错误:
Traceback (most recent call last):
File "c:\Users\David Amsalem\Desktop\Tech\python\core python appliction programing\exercise\chapter 1\01\script.py", line 6, in <module>
res = re.match('patt', data)
File "C:\Users\David Amsalem\AppData\Local\Programs\Python\Python37-32\lib\re.py", line 173, in match
return _compile(pattern, flags).match(string)
TypeError: expected string or bytes-like object
解决方案
re.match 函数适用于单个字符串。但是您可以像这样过滤字符串列表或元组:
import re
data = ('bat', 'bit', 'but','gdt', 'hat', 'hit', 'hut', 'hdg', 'grt')
patt = r'[bh][aiu]t'
r = re.compile(patt)
print(list(filter(r.match, data)))
给你:
['bat', 'bit', 'but', 'hat', 'hit', 'hut']
推荐阅读
- python - 无法从模块导入名称 X
- in-app-purchase - 苹果应用购买中用户升级订阅怎么办
- javascript - 为什么在 React 中更新数据时计时器无法正常工作?
- java - Spring boot webclient 2gb xml数据获取io.netty.handler.timeout.ReadTimeoutException:null
- python - 验证 Python 中离散值的独立性和均匀分布?
- c# - 停止 vscode 翻译警告/错误
- flutter - 可扩展的 ListView 颤动
- typescript - 类型映射和折叠`number | (str: string) => void` 到 `number | 字符串`
- javascript - 使用 ajax 调用填充文本字段
- database - Github 存储库统计:历史数据?