Dive Into Python Python for experienced programmers |

## 1.12. 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 in C.

Example 1.29. Introducing string formatting

    >>> k = "uid"
    >>> v = "sa"
    >>> "%s=%s" % (k, v)
    'uid=sa'

| The whole expression evaluates to a string. The first `%s` is replaced by the value of `k`; the second `%s` is replaced by the value of `v`. All other characters in the string (in this case, the equals sign) stay as they are.

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.

Example 1.30. String formatting vs. concatenating

    >>> 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

| `+` is the string concatenation operator.
| In this trivial case, string formatting accomplishes the same result as concatentation.
| `(userCount, )` is a tuple with one element. Yes, the syntax is a little strange, but there's a good reason for it: it's unambiguously a tuple. In fact, you can always include a comma after the last element when defining a list, tuple, or dictionary, but the comma is required when defining a tuple with one element. If the comma weren't required, Python wouldn't know whether `(userCount)` was a tuple with one element or just the value of `userCount`.
| String formatting works with integers by specifying `%d` instead of `%s`.
| Trying to concatenate a string with a non-string raises an exception. Unlike string formatting, string concatenation only works when everything is already a string.

Further reading

- Python Library Reference summarizes all the string formatting format characters.
- Effective AWK Programming discusses all the format characters and advanced string formatting techniques like specifying width, precision, and zero-padding.