[Tutor] Regexp result

Karl Pflästerer sigurd at 12move.de
Wed Jan 21 18:31:56 EST 2004


On 21 Jan 2004, Helge Aksdal <- python at aksdal.net wrote:

> Is there anyway that i can put regexp results into strings?
> In Perl i use qr for that operation:
> [...]
> qr '(\w\w\w)\s(\d+?)\s(\d\d:\d\d:\d\d)',
> q  '($month, $day, $time) = ($1, $2, $3)',
> [...]

There are some ways; it depends on the kind of verbosity you can accept.

First the most ovious way.

In [11]: re = sre.compile(r'(\w\w\w)\s(\d+?)\s(\d\d:\d\d:\d\d)')

In [12]: s = 'Jan 12 12:12:12'

In [13]: [(mon, day, time)] = re.findall(s)

In [14]: mon, day, time
Out[14]: ('Jan', '12', '12:12:12')

In [15]: mon
Out[15]: 'Jan'


That will only work if you have a match; then `findall' will return here
a list with one tuple which has three elements (one for every group in
the regexp).

So you have to write a little bit more code.

In [16]: re.findall("foo")
Out[16]: []

In [17]: re.findall("foo") or '','',''
Out[17]: (None, None, None)

Here you see what happens if there is no match; an empty list is
returned.  Since that's like a boolean false value we can use `or' to
return a three element tuple so Python doesn't complain.

In [21]: [(mon, day, time)] = re.findall('foo') or [('', '', '')]

In [22]: mon
Out[22]: ''

In [23]:


Instead of the above you could write code with `try' and `except' or you
could compute a match object, see if it is not none and assign the
values.  Or you could give each group a name and use the groupdict
(would be totally overkill here but naming groups is a nice feature).
So pick your favorite.



   Karl
-- 
Please do *not* send copies of replies to me.
I read the list




More information about the Tutor mailing list