Raghavendra S S
Raghavendra S S

Reputation: 115

trying to regex in python

Can anyone please help me understand this code snippet, from http://garethrees.org/2007/05/07/python-challenge/ Level2

>>> import urllib
>>> def get_challenge(s):
...     return urllib.urlopen('http://www.pythonchallenge.com/pc/' + s).read()
...
>>> src = get_challenge('def/ocr.html')
>>> import re
>>> text = re.compile('<!--((?:[^-]+|-[^-]|--[^>])*)-->', re.S).findall(src)[-1]
>>> counts = {}
>>> for c in text: counts[c] = counts.get(c, 0) + 1
>>> counts

http://garethrees.org/2007/05/07/python-challenge/

re.compile('<!--((?:[^-]+|-[^-]|--[^>])*)-->', re.S).findall(src)[-1] why we have [-1] here what's the purpose of it? is it Converting that to a list? **

Upvotes: 1

Views: 63

Answers (2)

Joost
Joost

Reputation: 4134

Yes. re.findall() returns a list of all the matches. Have a look at the documentation.

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.

When calling [-1] on the result, the first element from the end of the list is accessed.

For example;

>>> a = [1,2,3,4,5]
>>> a[-1]
5

And also:

>>> re.compile('.*?-').findall('-foo-bar-')[-1]
'bar-'

Upvotes: 1

leekaiinthesky
leekaiinthesky

Reputation: 5593

It's already a list. And if you have a list myList, myList[-1] returns the last element in that list.

Read this: https://docs.python.org/2/tutorial/introduction.html#lists.

Upvotes: 0

Related Questions