{article Dive into Python}{title} {text}{/article}

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.

  1. print ("Today's stock price: %f" % 50.4625)
  2. print ("Today's stock price: %.2f" % 50.4625)
  3. print ("Today's stock price: %+.2f" % 1.5)

  1. The %f string formatting option treats the value as a decimal, and prints it to six decimal places.
  2. The ".2" modifier of the %f option truncates the value to two decimal places.
  3. You can even combine modifiers. Adding the + modifier displays a plus or minus sign before the value. Note that the ".2" modifier is still in place, and is padding the value to exactly two decimal places.
ConversionMeaning
%d Signed integer decimal.
%i Signed integer decimal.
%o Signed octal value.
%u Obsolete type – it is identical to 'd'.
%x Signed hexadecimal (lowercase).
%X Signed hexadecimal (uppercase).
%e Floating point exponential format (lowercase).
%E Floating point exponential format (uppercase).
%f Floating point decimal format.
%F Floating point decimal format.
%g Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.
%G Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.
%c Single character (accepts integer or single character string).
%r String (converts any Python object using repr()).
%s String (converts any Python object using str()).
% No argument is converted, results in a '%' character in the result.


How to print a string


>>> string = "# How to print a string."
>>> print (string)
# How to print a string.

>>> print string
SyntaxError: invalid syntax


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


Concatenating

>>> uid = "sa"
>>> pwd = "secret"
1: >>> print pwd + " is not a good password for " + uid
SyntaxError: invalid syntax
>>> 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)
SyntaxError: invalid syntax
>>> print ("%s is not a good password for %s") % (pwd, uid)
%s is not a good password for %s
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
print ("%s is not a good password for %s") % (pwd, uid)
TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple'
2: >>> print ("%s is not a good password for %s" % (pwd, uid))
secret is not a good password for sa
>>> userCount = 6
3: 4: >>> print ("Users connected: %d" % (userCount, ))
Users connected: 6
5: >>> print ("Users connected: " + userCount)
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
print ("Users connected: " + userCount)
TypeError: Can't convert 'int' object to str implicitly
>>>

  1. + is the string concatenation operator.

  2. In this trivial case, string formatting accomplishes the same result as concatentation.

  3. (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.

  4. String formatting works with integers by specifying %d instead of %s.

  5. Trying to concatenate a string with a non−string raises an exception. Unlike string formatting, string
    concatenation works only when everything is already a string.


As with printf in C, string formatting in Python is like a Swiss Army knife. There are options galore, and modifier
strings to specially format many different types of values.


Numbers

>>> print("{:.2f}".format(3.1415926)) 2 decimal places
3.14
>>> print("{:+.2f}".format(+3.1415926)) 2 decimal places with sign
+3.14
>>> print("{:+.2f}".format(-1)) 2 decimal places with sign
-1.00
>>> print("{:.0f}".format(2.71828)) No decimal places
3
>>> print("{:0>2d}".format(5)) Pad number with zeros (left padding, width 2)
05
>>> print("{:x<4d}".format(5)) Pad number with x's (right padding, width 4)
5xxx
>>> print("{:x<4d}".format(10)) Pad number with x's (right padding, width 4)
10xx
>>> print("{:,}".format(1000000)) Number format with comma separator
1,000,000
>>> print("{:.2%}".format(0.25)) Format percentage
25.00%
>>> print("{:.2e}".format(1000000000)) Exponent notation
1.00e+09
>>> print("{:10d}".format(13)) Right aligned (default, width 10)
13
>>> print("{:<10d}".format(13)) Left aligned (width 10)
13
>>> print("{:^10d}".format(13)) Center aligned (width 10)
13

Type

Meaning

'e'

Exponent notation. Prints the number in scientific notation using the letter ‘e’ to indicate the exponent. The default precision is 6.

'E'

Exponent notation. Same as 'e' except it uses an upper case ‘E’ as the separator character.

'f'

Fixed point. Displays the number as a fixed-point number. The default precision is 6.

'F'

Fixed point. Same as 'f', but converts nan to NAN and inf to INF.

'g'

General format. For a given precision p >= 1, this rounds the number to p significant digits and then formats the result in either fixed-point format or in scientific notation, depending on its magnitude.

The precise rules are as follows: suppose that the result formatted with presentation type 'e' and precision p-1 would have exponent exp. Then if -4 <= exp < p, the number is formatted with presentation type 'f' and precision p-1-exp. Otherwise, the number is formatted with presentation type 'e' and precision p-1. In both cases insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it.

Positive and negative infinity, positive and negative zero, and nans, are formatted as inf, -inf, 0, -0 and nan respectively, regardless of the precision.

A precision of 0 is treated as equivalent to a precision of 1. The default precision is 6.

'G'

General format. Same as 'g' except switches to 'E' if the number gets too large. The representations of infinity and NaN are uppercased, too.

'n'

Number. This is the same as 'g', except that it uses the current locale setting to insert the appropriate number separator characters.

'%'

Percentage. Multiplies the number by 100 and displays in fixed ('f') format, followed by a percent sign.

None

Similar to 'g', except with at least one digit past the decimal point and a default precision of 12. This is intended to match str(), except you can add the other format modifiers.

OptionMeaning
'<' Forces the field to be left-aligned within the available space (this is the default for most objects).
'>' Forces the field to be right-aligned within the available space (this is the default for numbers).
'=' Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form ‘+000000120’. This alignment option is only valid for numeric types.
'^' Forces the field to be centered within the available space.