Search code examples
pythontimeutcpython-re

TypeError: expected string or bytes-like object in re


I want to grab 'Asia/Tel_Aviv' and 'Asia/Jeruslam' from this huge list, here is the full code:

import pytz
alltmzn=pytz.alltimezones
print(alltmzn)
t=alltmzn[234:332]
for i in re.findall("^J|Tel",t):
     print(i)

error:

TypeError                                 Traceback (most 
recent call last)
<ipython-input-133-fe8a33f8999a> in <module>
       1 t=alltmzn[234:332]
 ----> 2 for i in re.findall("^J|Tel",t):
       3     print(i)

C:\ProgramData\Anaconda3\lib\re.py in findall(pattern, string, flags)
239 
240     Empty matches are included in the result."""
 --> 241     return _compile(pattern, flags).findall(string)
242 
243 def finditer(pattern, string, flags=0):

TypeError: expected string or bytes-like object`

 

Solution

  • t is a list, while findall expects a string.

    You can rewrite it this way:

    for tz in t:
      if re.search(pattern, tz):
        print(tz)
    

    Note that your pattern will match strings starting with "Tel" or "Jel" (not Jer, and not including "Asia/" before), which is probably not what you want.