Formatting strings with

This section covers formatting strings with the string modulus (%) operator. It's used to combine Python values into formatted strings for printing or other use. C users will notice a strange similarity to the printf family of functions. The use of % for string formatting is the old style of string formatting, and I cover it here because it was the standard in earlier versions of Python and you're likely to see it in code that's been ported from earlier versions of Python or was written by coders familiar with those versions. This style of formatting shouldn't be used in new code, because it's slated to be deprecated and then removed from the language in the future. Here's an example:

>>> "%s is the %s of %s" % ("Ambrosia", "food", "the gods") 'Ambrosia is the food of the gods'

The string modulus operator (the bold % that occurs in the middle, not the three instances of %s that come before it in the example) takes two parts: the left side, which is a string; and the right side, which is a tuple. The string modulus operator scans the left string for special formatting sequences and produces a new string by substituting the values on the right side for those formatting sequences, in order. In this example, the only formatting sequences on the left side are the three instances of %s, which stands for "stick a string in here."

Passing in different values on the right side produces different strings:

>>> "%s is the %s of %s" % ("Nectar", "drink", "gods") 'Nectar is the drink of gods'

>>> "%s is the %s of the %s" % ("Brussels Sprouts", "food", ... "foolish")

'Brussels Sprouts is the food of the foolish'

The members of the tuple on the right will have str applied to them automatically by %s, so they don't have to already be strings:

>>> "The %s contains: %s" % ("list", x) "The list contains: [1, 2, 'three']"

Was this article helpful?

0 0

Post a comment