Search code examples
pythonstringformattingstring-formattingtext-formatting

How to format strings with tuples of values like using %(name)s


I've always seen formatting strings by placing tuples of values in between the modulo symbol and s character like using %(levelno)s:%(message)s from the Python logging module in a string for the fmt parameter argument for a Formatter instance would return the message and level number in the format string, and I have always wondered how it has created that format system. How do I make a formatting system like that?


Solution

  • I think what you're looking for is formatting strings by using the modulo operator (%s) as well as mapping format values using a dict, like this: print('Hello, %(name)s!' % {'name': 'Jack'})