How to use python regular expression to substitute string value
Pasi Savolainen
psavo at iki.fi
Sun Feb 26 16:23:07 EST 2006
Allerdyce.John at gmail.com writes:
> When I try your idea, I have this error
>
> x, y, width, height = re.findall(pattern, str)[0]
> IndexError: list index out of range
>
> How can I use findall to handle error case? i.e. what if there is no
> match? how can I handle it gracefully?
This is explained in python docs, and do try them in interactive python,
for example IPython is great for this stuff.
- -
ipython ->
In [1]:import re
In [2]:line = "foobar"
In [3]:re.findall ("baz", line)
Out[3]:[]
In [4]:re.findall ("o", line)
Out[4]:['o', 'o']
- -
So you can do:
- -
match = re.findall(pattern, str)
if match:
x, y, width, height = match[0]
...
else:
# no match
- -
--
Psi -- <http://www.iki.fi/pasi.savolainen>
More information about the Python-list
mailing list