Home > Dive Into Python > Getting To Know Python > Formatting strings | << >> |
diveintopython.org | |
Python for experienced programmers | |
All the real work of odbchelper.py is done in one line of code, and here it is.
return ";".join(["%s=%s" % (k, params[k]) for k in params.keys()])
Don't panic. Ignore everything else and focus on the middle part, which is a string formatting expression. (If you're a C hacker, you can probably skim this part.)
"%s=%s" % (k, params[k])
Python supports formatting values in strings, like the sprintf function in C. The most basic usage is to simply insert a value in the place of the %s placeholder.
Example 1.26. Introducing string formatting
>>> params = {"uid":"sa", "pwd":"secret"} >>> k = "uid" >>> "%s=%s" % (k, params[k])'uid=sa' >>> k = "pwd" >>> "%s=%s" % (k, params[k])
'pwd=secret'
Note that (k, params[k]) 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.
Example 1.27. String formatting vs. concatenating
>>> 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: %s" % (userCount, )
![]()
Users connected: 6 >>> print "Users connected: " + userCount
Traceback (innermost last): File "<interactive input>", line 1, in ? TypeError: cannot add type "int" to string
« Defining variables | Mapping lists » |