TypeError:re中应为string或byteslike对象

2024-10-03 23:26:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从这个巨大的列表中抓取“亚洲/特拉维夫”和“亚洲/杰鲁斯兰”,以下是完整的代码:

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

错误:

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`

 

Tags: 代码inimportre列表forstringflags
1条回答
网友
1楼 · 发布于 2024-10-03 23:26:22

t是一个列表,而findall需要一个字符串

您可以这样重写它:

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

请注意,您的模式将字符串开头与“Tel”或“Jel”(不是Jer,前面不包括“Asia/”)匹配,这可能不是您想要的

相关问题 更多 >