Python lambda if re.sub expression

Therefore, I use the following regular expression to parse text and capture information from a specific dictionary:

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

What I want to do is replace it only with what it replaces - this is the key in a separate dictionary. Logically, it will 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 need 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 replace only this way?

+7
source share
1 answer

An if expression always requires an else . You should always replace the corresponding text. If you do not want to replace it, you just need to replace it with yourself:

 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) 
+12
source

All Articles