Python f-string: replacing newline/linebreak

Question:

First off all, sorry: I’m quite certain this might be a “duplicate” but I didn’t succeed finding the right solution.

I simply want to replace all linebreaks within my sql-code for logging it to one line, but Python’s f-string doesn’t support backslashes, so:

# Works fine (but is useless ;))
self.logger.debug(f"Executing: {sql.replace( 'C','XXX')}")

# Results in SyntaxError: 
# f-string expression part cannot include a backslash
self.logger.debug(f"Executing: {sql.replace( 'n',' ')}")

Of course there are several ways to accomplish that before the f-string, but I’d really like to keep my “log the line”-code in one line and without additional helper variables.

(Besides I think it’s a quite stupid behavior: Either you can execute code within the curly brackets or you cant’t…not “you can, but only without backslashes”…)

This one isn’t a desired solution because of additional variables:

How to use newline 'n' in f-string to format output in Python 3.6?

General Update
The suggestion in mkrieger1s comment:

        self.logger.debug("Executing %s", sql.replace('n',' '))

Works fine for me, but as it doesn’t use f-strings at all (beeing that itself good or bad ;)), I think I can leave this question open.

Asked By: evilive

||

Answers:

You can do this

newline = 'n'
self.logger.debug(f"Executing: {sql.replace( newline,' ')}")
Answered By: Nithin
  1. don’t use f-strings, especially for logging
  2. assign the newline to a constant and use that, which you apparently don’t want to
  3. use an other version of expressing a newline, chr(10) for instance

(Besides I think it’s a quite stupid behavior: Either you can execute code within the curly brackets or you cant’t…not “you can, but only without backslashes”…)

Feel free to take a shot at fixing it, I’m pretty sure this restriction was not added because the PEP authors and feature developers wanted it to be a pain in the ass.

Answered By: Masklinn

I found possible solutions

from os import linesep

print(f'{string_with_multiple_lines.replace(linesep, " ")}')

Best,

Answered By: Joel Zamboni
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.