3.5. Formatting Strings
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 inC. |
Example 3.21. Introducing String Formatting
>>> k = "uid" >>> v = "sa" >>> "%s=%s" % (k, v) 1 'uid=sa'
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 would be right, except that string formatting isn't just concatenation. It's not even just formatting. It's also type coercion.
Example 3.22. String Formatting vs. Concatenating
>>> uid = "sa" >>> pwd = "secret" >>> print pwd + " is not a good password for " + uid 1 secret is not a good password for sa >>> print "%s is not a good password for %s" % (pwd, uid) 2 secret is not a good password for sa >>> userCount = 6 >>> print "Users connected: %d" % (userCount, ) 3 4 Users connected: 6 >>> print "Users connected: " + userCount 5 Traceback (innermost last): File "<interactive input>", line 1, in ? TypeError: cannot concatenate 'str' and 'int' objects
As with printf in C, string formatting inPython is like a Swiss Army knife. There are options galore, and modifier strings to specially
format many different types of values.
Example 3.23. Formatting Numbers
>>> print "Today's stock price: %f" % 50.4625 1 50.462500 >>> print "Today's stock price: %.2f" % 50.4625 2 50.46 >>> print "Change since yesterday: %+.2f" % 1.5 3 +1.50
############下面还有一篇相关文章#########