Consider the following Python code using the regex library re
import re
re.compile(rf"{''.join(['{c}\s*' for c in 'qqqq'])}")
I have run it in two different REPLs:
https://www.pythonmorsels.com/repl/
https://www.online-python.com/#google_vignette
The first of which gives no error, and the second give the following error:
File "main.py", line 2
re.compile(rf"{''.join(['{c}\s*' for c in 'qqqq'])}")
^
SyntaxError: f-string expression part cannot include a backslash
I’d like to understand why I get an error sometimes and not others. How can I proceed to narrow down exactly where the difference is?
6
The second one which gives the syntax error, is running Python 3.8.5, which was before PEP 701 was added to Python. PEP 701 finally added f-strings to the Python 3.12 parser so they can contain any valid expression which includes strings with a backslash. Pre-3.12 python postprocesses f-strings with a weird ad hoc parser that gets really confused when it sees a backlash inside an expression part.
Evidently the first online REPL that gives no error is running Python 3.12.
You can get around the problem with:
import re
re.compile("{0}".format(''.join([fr'{c}s*' for c in 'qqqq'])))
This works on both repls you provided. It sends ‘qs*qs*qs*qs*’ to re.compile.
I’m assuming that the ‘\s’ was meant to reduce to ‘s’.
2