Simple (I think) regex question

Tim Roberts timr at probo.com
Sat Nov 24 06:56:45 CET 2001


Michael Kelly <jedimike at mac.com> wrote:
>
>I've used Perl quite a bit, but am very new to Python, and am still getting
>used to things. I'm not sure if I'm explaining this correctly or clearly,
>but here goes:
>
>My question is this: In a sub(), how do set the replacement string to be as
>long as the first matched substring? (i.e., the len() of \1).

You'll have to do this in two steps.  Do the match; it will return the
start and length of the match.  You can use that information to do the
replacement.

Many "magic" perl constructs take longer to spell in Python.  Plus, you'll
find that the perl habit of thinking about every problem in terms of
regular expressions often produces sub-optimal results in Python.  However,
there is usually a way to look at the problem in terms of lists that
produces a more Python-like solution.
--
- Tim Roberts, timr at probo.com
  Providenza & Boekelheide, Inc.



More information about the Python-list mailing list