Question

Is there a good reference which directly compares examples of old % style string formatting with the equivalent in the newer .format way?

I'm looking for something along the lines of this table (which in that case compares matlab commands with the equivalent in numpy). This was instrumental in getting me up to speed when first learning Python.

For example...

╔═══════════════╦══════════════════════════╦════════╦═══════╗
║       %       ║         .format          ║ result ║ notes ║
╠═══════════════╬══════════════════════════╬════════╬═══════╣
║ "%.3f"%1.3579 ║ "{:.3f}".format(1.3579)  ║ 1.358  ║       ║
║ "%d"%1.35     ║ "{:d}".format(int(1.35)) ║ 1      ║ (1)   ║
║ ...           ║                          ║        ║       ║
╚═══════════════╩══════════════════════════╩════════╩═══════╝
(1) must explicitly cast to specified type in .format style formatting.
Was it helpful?

Solution

I'd say yes, there is, from the python documentation:

This section contains examples of the new format syntax and comparison with the old %-formatting.

here's a summary of what's in there:

| old   | new     | arg     | result      |
| ----- | ------- | ------- | --------    |
| `%s`  | `{!s}`  | `'foo'` | `foo`       |
| `%r`  | `{!r}`  | `'foo'` | `'foo'`     |
| `%c`  | `{:c}`  | `'x'`   | `x`         |
| `%+f` | `{:+f}` | `3.14`  | `+3.140000` |
| `% f` | `{: f}` | `3.14`  | ` 3.140000` |
| `%-f` | `{:-f}` | `3.14`  | `3.140000`  |
| `%d`  | `{:d}`  | `42`    | `42`        |
| `%x`  | `{:x}`  | `42`    | `2a`        |
| `%o`  | `{:o}`  | `42`    | `52`        |
| `∅`   | `{:b}`  | `42`    | `101010`    |

I guess the upper case equivalent work the same.

To prepend the digital base:

| old   | new     | arg     | result     |
| ----- | ------- | ------- | --------   |
| `%#d` | `{:#d}` | `42`    | `42`       |
| `%#x` | `{:#x}` | `42`    | `0x2a`     |
| `%#o` | `{:#o}` | `42`    | `052`      |
| `∅`   | `{:#b}` | `42`    | `0b101010` |

And to convert the number to scientific notation:

| old   | new     | arg       | result       |
| ----- | ------- | -------   | --------     |
| `%e`  | `{:e}`  | `0.00314` | 3.140000e-03 |

For the alignment, there is:

| old     | new      | arg     | result         |
| -----   | -------  | ------- | --------       |
| `%-12s` | `{:<12}` | `meaw`  | `        meaw` |
| `%+12s` | `{:>12}` | `meaw`  | `meaw        ` |

For filling:

| old     | new       | arg     | result         |
| -----   | -------   | ------- | --------       |
| `%012d` | `{:>012}` | `42`    | `000000000042` |

As you can see, most of the base symbols are the same between old format and new format. The main difference, is that the new format is a well defined language matching the following grammar:

format_spec ::=  [[fill]align][sign][#][0][width][.precision][type]

whereas the old format was a bit more voodoo.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top