表等同于新旧Python字符串格式

时间:2014-05-08 00:37:55

标签: python string formatting string-formatting

是否有一个很好的引用可以直接将旧%样式字符串格式的示例与较新.format方式的等效字符串进行比较?

我正在寻找this table行的内容(在这种情况下,将matlab命令与numpy中的等效命令进行比较)。这有助于我在第一次学习Python时加快速度。

例如......

╔═══════════════╦══════════════════════════╦════════╦═══════╗
║       %       ║         .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.

1 个答案:

答案 0 :(得分:0)

我说是的,有python documentation

  

本节包含新格式语法的示例以及与旧%格式化的比较。

这里是对其中的内容的总结:

| 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`    |

我猜大写的等效工作相同。

预装数字基地:

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

并将数字转换为科学记数法:

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

对于对齐,有:

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

填写:

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

如您所见,旧格式和新格式之间的大多数基本符号相同。主要区别在于新格式是一种定义良好的语言,与以下语法相匹配:

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

而旧的格式有点巫毒。

相关问题