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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With