7

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?

0

1 Answer 1

12

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)
Sign up to request clarification or add additional context in comments.

4 Comments

same syntax error...also why would the else statement go after the comma that seperates the replace statement from the text?
@RyanSaxe: Sorry, I made a typo and left the text in the wrong place, see the updated version. (You should put spaces after your commas! :-)
are the parentheses wrapping the lambda necessary?
@RyanSaxe: The parens are not necessary here, because it's not ambiguous to the parser whether the comma is inside the lambda body or the lambda is a comma-separated argument to re.sub. However, if it's not immediately obvious to you that it's not ambiguous, you may want to use them anyway, because code has to be meaningful to human readers, not just to the compiler.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.