您当前位置:首页 > 深入 Python > 原生数据类型 > 格式化字符串 | << >> | ||||
深入 Python从 Python 新手到专家 |
Python 支持将值格式化为字符串。 虽然这可以包含非常复杂的表达式,但最基本的用法是使用 %s 占位符将值插入字符串。
![]() |
|
Python 中的字符串格式化使用与 C 中的 sprintf 函数相同的语法。 |
请注意,(k, v) 是一个元组。 我告诉过你它们是有用的。
您可能认为这只是为了进行简单的字符串连接而做了很多工作,您是对的,但字符串格式化不仅仅是连接。 它甚至不仅仅是格式化。 它也是类型强制。
>>> uid = "sa" >>> pwd = "secret" >>> print pwd + " is not a good password for " + uidsecret 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 "<interactive input>", line 1, in ? TypeError: cannot concatenate 'str' and 'int' objects
与 C 中的 printf 一样,Python 中的字符串格式化就像一把瑞士军刀。 有很多选项,还有修饰符字符串可以专门格式化许多不同类型的值。
>>> print "Today's stock price: %f" % 50.4625Today's stock price: 50.462500 >>> print "Today's stock price: %.2f" % 50.4625
Today's stock price: 50.46 >>> print "Change since yesterday: %+.2f" % 1.5
Change since yesterday: +1.50
<< 声明变量 |
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | |
映射列表 >> |