[Tutor] Regexp result
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 : re = sre.compile(r'(\w\w\w)\s(\d+?)\s(\d\d:\d\d:\d\d)')
In : s = 'Jan 12 12:12:12'
In : [(mon, day, time)] = re.findall(s)
In : mon, day, time
Out: ('Jan', '12', '12:12:12')
In : mon
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
So you have to write a little bit more code.
In : re.findall("foo")
In : re.findall("foo") or '','',''
Out: (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 : [(mon, day, time)] = re.findall('foo') or [('', '', '')]
In : mon
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.
Please do *not* send copies of replies to me.
I read the list
More information about the Tutor