【问题标题】:String-format placeholders for maximum compatibility with python 2.6, 2.7 and 3.x与 python 2.6、2.7 和 3.x 最大兼容的字符串格式占位符
【发布时间】:2015-09-23 06:47:31
【问题描述】:

我应该将哪些占位符与字符串的.format()-method 结合使用,以便在与 python 解释器的 2.6、2.7 和 3.x(在我的情况下为 3.2)一起使用时兼容?

我开始使用 {:} 占位符,但这不适用于 2.6。现在我正在使用{<index-of-format-tuple>},它似乎适用于所有列出的版本。

有更好的选择吗?性能不是问题,兼容性才是问题。

【问题讨论】:

  • 无论如何,您都需要在支持{}(冒号是多余的)的版本中指定各种情况下的索引(例如,如果一个参数被多次使用),所以我会坚持使用索引。

标签: python python-2.7 python-3.x python-2.6


【解决方案1】:

这是 Python 2.6 中字符串格式化的手册:https://docs.python.org/2.6/library/string.html#format-string-syntax

里面的所有东西都应该得到支持,没有问题。

我个人一般选择 c 风格的字符串格式:https://docs.python.org/2/library/stdtypes.html#string-formatting-operations

在大多数情况下,它工作得很好,而且对我来说更熟悉。它仍然支持相当高级的格式:

>>> print '%(language)s has %(number)03d quote types.' % \
...       {"language": "Python", "number": 2}
Python has 002 quote types.

【讨论】:

    猜你喜欢
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多