David Amsalem
David Amsalem

Reputation: 13

"Expected string or bytes-like object" using re.match() against a tuple

I don't have anyone who's coding in my area i'd love if someone can help!

I'm using vs code

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()

I need to match pattern to bat,bet,bit,hut. However, I get these errors:

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

Upvotes: 1

Views: 767

Answers (1)

J&#246;rg Beyer
J&#246;rg Beyer

Reputation: 3671

The re.match function works on a single string. But you can filter a list or tuple of strings like this:

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)))

gives you:

['bat', 'bit', 'but', 'hat', 'hit', 'hut']

Upvotes: 1

Related Questions