Python re.findall打印列表而不是字符串

时间:2015-08-18 20:33:46

标签: python regex urllib2

address = ('http://www.somesite.com/article.php?page=' +numb)
html = urllib2.urlopen(address).read()
regex = re.findall(r"([a-f\d]{12})", html)

如果您运行脚本,输出将类似于此:

['aaaaaaaaaaaa', 'bbbbbbbbbbbb', 'cccccccccccc']

如何让脚本打印此输出(注意换行符):

aaaaaaaaaaaa
bbbbbbbbbbbb
cccccccccccc

任何帮助?

3 个答案:

答案 0 :(得分:1)

re.findall()返回一个列表。因此,你可以迭代列表并分别打印出每个元素:

address = ('http://www.somesite.com/article.php?page=' +numb)
html = urllib2.urlopen(address).read()
for match in re.findall(r"([a-f\d]{12})", html)
    print match

或者你可以这样做@bigOTHER建议并将列表一起加入一个长字符串并打印字符串。它基本上做同样的事情。

来源:https://docs.python.org/2/library/re.html#re.findall

  

re.findall(pattern,string,flags = 0)返回所有非重叠   字符串中的模式匹配,作为字符串列表。字符串是   从左到右扫描,并按找到的顺序返回匹配。如果   模式中存在一个或多个组,返回列表   组;如果模式有多个,这将是一个元组列表   组。结果中包含空匹配,除非他们触摸了   另一场比赛的开始。

答案 1 :(得分:0)

只需打印regex,就像这样:

print "\n".join(regex)
address = ('http://www.somesite.com/article.php?page=' +numb)
html = urllib2.urlopen(address).read()
regex = re.findall(r"([a-f\d]{12})", html)
print "\n".join(regex)

答案 2 :(得分:0)

对结果使用join

"".join("{0}\n".format(x) for x in re.findall(r"([a-f\d]{12})", html)
相关问题