To include a newline inside the f-string, like in Patrick's answer, but have it in one line, I use eval
:
print(eval('f"""{df=\n}"""'))
df=
animal
0 alligator
1 bee
2 falcon
3 lion
4 monkey
Use triple-single quotes to allow single-quotes inside, for example:
print(eval('''f"""{df.query('animal.str.contains("e")')=\n}"""'''))
df.query('animal.str.contains("e")')=
animal
1 bee
4 monkey
If you include a conversion, it needs to go after the newline (e.g. ...\n!s}
...), otherwise you get a SyntaxError
. Same for a format spec, but with a ValueError
you'd get from a non-eval'd f-string.
I put it in a code snippet so I don't have to type/remember the whole thing every time. For VSCode:
"Dead-simple debug using f-string with newline before value": {
"prefix": "debug-fstring-newline",
"body": "print(eval('''f\"\"\"DEBUG: {${1:<expression>}=\\n${2:!${3:<conversion>}}${4::${5:<format_spec>}}}\"\"\"'''))",
},
P.S. I initially tried inserting a newline via a variable, but this syntax is invalid:
NL = '\n'
print(f"{df={NL}}")