首页 > 解决方案 > 对元组使用 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

标签: python

解决方案


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']

推荐阅读