Python string formatting
Code Mastery,  Featured

String formatting like a pro

Just about every Python programmer has used the ‘%’ operator for string formatting. But another formatting method is available using the .format()  method of the string object. This allows for much cleaner and more readable code than the incantations written using ‘%’ operators.

Basic string formatting

Basic string formatting works by using small template tags in the string you want to format:

The method above uses positional arguments, where each argument to the format function is identified by a zero-based index.

But you can also format strings using more elaborate field names and keyword arguments

Or even passing entire class instances that you can identify by field names:

Update: Since Python 2.7 it’s possible to omit the names or indexes of your positional arguments in your template string. This can improve your coding speed since you don’t have to name or refer to your arguments by index. The arguments are automatically used in the order you specify them.
Beware that you don’t clutter your code or sacrifice readability, when using multiple arguments I would recommend naming them by using keywords or using the index based approach.

Format specifiers

Just like the ‘%’ operator there are a multitude of format specifiers available to change the output of the templating. The entire list of options for string formatting is available at the documentation link at the bottom of this article.

Here are some examples of how you can format your strings using the languages specifiers. Aligning and padding for example:

or the often used precision formatter:

 

More information

The .format() method is based on PEP3101 and here is the complete documentation on the format mini-language.

3 Comments

  • papahippo

    What about the old-fashioned ‘modulo’ operator formatting (e.g ‘%2d’ % answer); is this so out-of-favour that even talking about it is regarded as unpythonic?

    • JimBroad

      I don’t read this as saying ‘modulo’ using is unpythonic, but think the first paragraph explains the author’s intent to bring attention to this alternative to using ‘modulo’ when formatting strings. (For those unaware, or who have forgotten about it — ‘modulo’ works well enough for may not to bother looking further)

      An example of a more complex(longer) string requiring formatting with many substitutions would probably highlight where the improved readability would come in handy. Something like a welcome email, etc…

Leave a Reply

Your email address will not be published. Required fields are marked *