3

Suppose, I want to convert the following .format()'ed string to a f'...' expression:

self.logger.debug('{:10} -- {}'.format('Jira', 'Scan: {} '.format(self.scan_id)))

I can do it easily as:

self.logger.debug(f'Jira      -- {self.scan_id}`)

However, I don't want to add the spaces (width) around 'Jira' manually. How can I do that without first having to create a new variable as in:

s='Jira'
self.logger.debug(f'{s:10} -- {self.scan_id}`)

?

Shuzheng
  • 11,288
  • 20
  • 88
  • 186

2 Answers2

7

You can directly put your string in curly brackets like this:

self.logger.debug(f'{"Jira":10} -- {self.scan_id}')

Because an f-string expects an expression inside {} and a string itself is a valid expression.

Asocia
  • 5,935
  • 2
  • 21
  • 46
2

You should generally avoid doing string formatting directly in logging calls as it can waste time formatting strings that are never emitted. Instead you should prefer to use the inbuilt formatting of the logger.

An example of how you might achieve your logging call would be:

logger.debug('% -10s -- %s', 'Jira', self.scan_id)

By default, the logging module uses percent formatting (documentation). If you are more familar with brace formatting (ie.using {}) and would prefer to use that, then this answer shows you how to set it up.

Dunes
  • 37,291
  • 7
  • 81
  • 97
  • Can't I just set the formatting using the `style='%'` parameter of `logging.Formatter.__init__`? – Shuzheng May 12 '20 at 08:41
  • No, because that refers to the formatter template. The linked question is about getting brace formatting working with the message template. The formatter template refers to the entire line that gets emitted, of which the message template is a part of. The formatter template might include things like level, time, logger name, etc... eg. `logging.Formatter('{asctime} {name} {levelname:8s} {message}', style='{')`. The `message` template in this answer would be `'% -10s -- %s'`. – Dunes May 12 '20 at 11:12