[Tutor] Newbie: Passing variable into re.compile
Kent Johnson
kent37 at tds.net
Thu Mar 30 01:24:30 CEST 2006
Jerome Jabson wrote:
> Hello,
>
>
>
> I’m having trouble trying to pass a variable into
> re.compile(), using the “r” option. Let’s say I
> have the following:
>
>
>
> import re
>
> arg1 = ‘10”
>
> p = re.compile(r + arg1 + '\.(\d+\.\d+\.\d+)')
>
>
>
> This works if I do:
>
>
>
> p = re.compile(r ‘10\.(\d+\.\d+\.\d+)')
>
>
>
> Is there something special I need to do for the
> “r” option? Like escape it when using a variable?
'r' is not an option to re.compile(), it is a modifier for the string
itself that affects how the string is parsed. So you can use
p = re.compile(arg1 + r'\.(\d+\.\d+\.\d+)')
or use string substitution as John suggests.
Kent
More information about the Tutor
mailing list