Use variable in regular expression

Sion Arrowsmith siona at
Thu Aug 2 13:44:56 CEST 2007

 <CarpeSkium at> wrote:
>I know I can use a variable in regular expressions. I want to use a
>regex to find something based on the beginning of the string.

You're coming from a Perl background, right? No-one else would
think of using a regexp for such a simple thing. There are two
things you need to learn:

(a) Python doesn't do automatic variable interpolation in strings.
(b) For simple find and replace operations, there are string
    methods which are easier and faster than regexps.

>Yesterday's date is 20070731, and assigned to the variable
>"yesterday_date". I want to loop thru a directory and find all of the
>yesterday's data ONLY IF the feature class has the date at the
>BEGINNING of the filename.
>Sample strings:
>I don't want the one's that start with "Copy".

>>> "20070731_test1".startswith(yesterday_date)
>>> "Copy20070731_test1".startswith(yesterday_date)

\S -- siona at --
   "Frankly I have no feelings towards penguins one way or the other"
        -- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump

More information about the Python-list mailing list