Use variable in regular expression

Sion Arrowsmith siona at chiark.greenend.org.uk
Thu Aug 2 07:44:56 EDT 2007


 <CarpeSkium at gmail.com> 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:
>20070731_test1
>Copy20070731_test1
>20070731_test2
>Copy20070731_test2
>20070731_test3
>Copy20070731_test3
>
>I don't want the one's that start with "Copy".

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

-- 
\S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
   "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