You are here: Home > Dive Into Python > Getting To Know Python > Formatting strings | << >> | ||||
Dive Into PythonPython for experienced programmers |
Python supports formatting values into strings. Although this can include very complicated expressions, the most basic usage is to insert values into a string with the %s placeholder.
String formatting in Python uses the same syntax as the sprintf function in C. |
Note that (k, v) is a tuple. I told you they were good for something.
You might be thinking that this is a lot of work just to do simple string concatentation, and you’d be right, except that string formatting isn’t just concatenation. It’s not even just formatting. It’s also type coercion.
>>> 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
<< Assigning multiple values at once |
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | |
Mapping lists >> |