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

Python re.findall prints list instead of string

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

有什么帮助吗?

re.findall() returns 一个列表。因此,您可以像这样遍历列表并分别打印出每个元素:

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) Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match.

像这样打印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)

对结果使用join

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