Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python lambda if statement re.sub

So I am using the following regex to parse text and grab information from a specific dictionary:

re.sub(r'(<Q\d+>)',lambda m: quotes[m.group(1)][1],text)

What I want to do, is only have it replace if what it would replace with is a key in a separate dictionary. Logically it would look like this:

re.sub(r'(<Q\d+>)',lambda m: quotes[m.group(1)][1] if quotes[m.group(1)][1] in d,text)

now if I were to run the following, I get the following syntax error:

>>> re.sub(r'(<Q\d+>)',lambda m: quotes[m.group(1)][1] if quotes[m.group(1)][1] in d,text)
  File "<stdin>", line 1
    re.sub(r'(<Q\d+>)',lambda m: quotes[m.group(1)][1] if quotes[m.group(1)][1] in d,text)
                                                                                    ^
SyntaxError: invalid syntax

How can I only replace in this way?

like image 426
Ryan Saxe Avatar asked Sep 20 '13 17:09

Ryan Saxe


1 Answers

The if expression always requires an else. You always have to replace the matched text. If you don't want to replace it, you just need to replace it with itself:

re.sub(r'(<Q\d+>)', 
  (lambda m: quotes[m.group(1)][1] if quotes[m.group(1)][1] in d else m.group(1)), text)
like image 143
BrenBarn Avatar answered Nov 18 '22 19:11

BrenBarn