Python数字格式 [英] Python numbers formatting
问题描述
什么是
%。2f%x
$ p $ ($)
$ {$。
我有些困惑,应该使用哪种方法以及哪种版本的Python。
一般而言,您希望使用第二个表单( .format()
)它是更新的,另一个最终会消失(至少这是一个意图 - 下面见 Notes )。
引用Python Python 3.0中的新增功能 docs:
用于内置字符串格式化操作的新系统将替换%
字符串格式操作符。 (但是,%运算符仍然支持
;它将在Python 3.1中被弃用,并在稍后时间从
语言中删除。)阅读PEP 3101以获取全文。
.format()
已经可用,因为至少Python 2.6
有关高级字符串格式化(PEP 3101)
$ b :
@Duncan也提到了引用一个线程,讨论是否/何时%
格式将在下面的评论中消失。而@NedBatchelder有这个明确的引用来自 Python 3.2文档: ...目前没有计划放弃使用printf风格的格式。
Possible Duplicate:
String formatting options: pros and cons
What's the difference between
"%.2f" % x
and
"{:.2f}".format(x)
I am a bit confused about which method should I use and for which version of Python.
In general you want to use the 2nd form (.format()
) it's newer and the other one will eventually go away (at least that was the intention at some point - see Notes below).
To quote the Python What’s New In Python 3.0 docs:
A new system for built-in string formatting operations replaces the % string formatting operator. (However, the % operator is still supported; it will be deprecated in Python 3.1 and removed from the language at some later time.) Read PEP 3101 for the full scoop.
.format()
has been available since at least Python 2.6
More information about Advanced String Formatting (PEP 3101)
Notes:
@Duncan also mentions a reference to a thread that discusses whether/when the %
based formatting will go away in the comments below. And @NedBatchelder has this definite quote from the Python 3.2 docs: "... there are no current plans to deprecate printf-style formatting.
"
这篇关于Python数字格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!