首页 > 深入Python > 开始了解Python > 格式化字符串 | << >> | ||||
diveintopython.org Python for experienced programmers |
Python支持将值的格式化输出到字符串中。尽管这样可能包括非常复杂的表达式,但最基本的用法是将一个值插入到一个有着字符串有 %s 占位符的字符串中。
在Python中,字符串格式化使用与C中 sprintf 函数一样的语法。 |
>>> k = "uid" >>> v = "sa" >>> "%s=%s" % (k, v) 'uid=sa'
你可能一直在想做了这么多工作只是为了做简单的字符串连接,你想的不错;只不过字符串格式化不只是连接。它甚至不仅仅是格式化。它也是强制类型转换。
>>> 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 "<interactive input>", line 1, in ? TypeError: cannot add type "int" to string
进一步阅读
一次赋多值 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
映射列表 |