我想在python中的"match objects“中找到一个字符串,但是".find”不起作用。这是我的片段:
e_list = []
for file in os.listdir('.'):
r = re.compile(r".*\.(aaa|bbb)$")
e_found = r.search(file)
if e_found is not None:
e_list.append(e_found.group(0))
e_length = len(e_list);
for num_e in range(e_length):
if(e_list[num_e].group(0).find('50M') > 0)
print(e_list[num_e].group(0))..。现在,e_list就像:
[<_sre.SRE_Match object; span=(0, 7), match='30M.aaa'>,
<_sre.SRE_Match object; span=(0, 7), match='40M.bbb'>,
<_sre.SRE_Match object; span=(0, 7), match='50M.aaa'>,
<_sre.SRE_Match object; span=(0, 7), match='50M.bbb'>,
<_sre.SRE_Match object; span=(0, 7), match='50M.ccc'>]我希望结果是:
'50M.aaa'
'50M.bbb'当e_list[0].group(0)返回'30M.aaa'时,不能应用.find,因为它是一个匹配对象。那我该怎么办?
发布于 2016-08-12 02:13:43
我认为Python不是您的第一语言,您的代码闻起来像Java。
请不要使用re.compile,因为它是不必要的。只需使用re.search或re.findall。
在Python中,您只需使用:
result = re.findall('.*\.(aaa|bbb)$', file)然后,result是一个列表,您可以打印它或使用for... loop获取它的每一项。
您还可以使用:
result = re.search('.*\.(aaa|bbb)$', file)结果是一群人。
然后,您应该使用result.group(1)来获取匹配的项。
因此,您的代码可以是:
e_list = []
for file in os.listdir('.'):
e_found = re.search(".*\.(aaa|bbb)$", file)
if e_found:
e_list.append(e_found.group(1))
for item in e_list:
if item.find('50M') > 0
print(item)发布于 2016-08-12 02:06:40
若要检查字符串是否以'50M'开头,请使用str.startswith('50M')。这不会检测到50M是后缀(test.50M)的情况。
if e_list[num_e].startswith('50M'):
print(e_list[num_e])如果后缀是查找50M的合法位置,那么使用in要比.find('50M') > 0干净得多。
if '50M' in e_list[num_e]:https://stackoverflow.com/questions/38908699
复制相似问题