Search code examples
pythonpython-3.7f-string

Python f-string: replacing newline/linebreak


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.


Solution

  • I found possible solutions

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

    Best,