Python 支持格式化字符串的输出 。尽管这样可能会用到非常复杂的表达式, 但最基本的用法是将一个值插入到一个有字符串格式符 %s 的字符串中。
| 在 Python 中, 字符串格式化使用与 C 中 sprintf 函数一样的语法。 | |
注意 (k, v) 是一个 tuple。 我说过它们对某些东西有用。
您可能一直在想做了这么多工作只是为了做简单的字符串连接, 您想的不错, 只不过字符串格式化不只是连接。它甚至不仅仅是格式化。它也是强制类型转换。
例 3.22. 字符串格式化与字符串连接的比较
>>> uid = "sa" >>> pwd = "secret" >>> print pwd + " is not a good password for " + uid secret is not a good password for sa >>> print "%s is not a good password for %s" % (pwd, uid) secret is not a good password for sa >>> userCount = 6 >>> print "Users connected: %d" % (userCount, ) Users connected: 6 >>> print "Users connected: " + userCount Traceback (innermost last): File "", line 1, in ? TypeError: cannot concatenate 'str' and 'int' objects
如同 printf 在 C 中的作用, Python 中的字符串格式化是一把瑞士军刀。 它有丰富的选项, 不同的格式化格式符和可选的修正符用于不同的数据类型。
例 3.23. 数值的格式化
>>> print "Today's stock price: %f" % 50.4625 50.462500 >>> print "Today's stock price: %.2f" % 50.4625 50.46 >>> print "Change since yesterday: %+.2f" % 1.5 +1.50
没有评论:
发表评论