re.sub and variables

fuglyducky fuglyducky at gmail.com
Thu Aug 12 17:33:28 EDT 2010


On Aug 12, 2:06 pm, fuglyducky <fuglydu... at gmail.com> wrote:
> I have a function that I am attempting to call from another file. I am
> attempting to replace a string using re.sub with another string. The
> problem is that the second string is a variable. When I get the
> output, it shows the variable name rather than the value. Is there any
> way to pass a variable into a regex?
>
> If not, is there any other way to do this? I need to be able to dump
> the variable value into the replacement string.
>
> For what it's worth this is an XML file so I'm not afraid to use some
> sort of XML library but they look fairly complicated for a newbie like
> me.
>
> Also, this is py3.1.2 is that makes any difference.
>
> Thanks!!!
>
> #####################################################
>
> import random
> import re
> import datetime
>
> def pop_time(some_string, start_time):
>     global that_string
>
>     rand_time = random.randint(0, 30)
>     delta_time = datetime.timedelta(seconds=rand_time)
>
>     for line in some_string:
>         end_time = delta_time + start_time
>         new_string = re.sub("thisstring", "thisstring\\end_time",
> some_string)
>         start_time = end_time
>
>     return new_string

Disregard...I finally figured out how to use string.replace. That
appears to work perfectly. Still...if anyone happens to know about
passing a variable into a regex that would be great.



More information about the Python-list mailing list