Format
It’s time we look at how to interpolate data values into strings—in other words, put the values inside the strings—using various formats ( place holder).
Old style with %
simply sequence is a % followed by a letter indicating the data type to be formatted.
%s – string
%d- decimal integer
%x – hex integer
%o – octal integer
%f – decimal float
%e – exponential float
%g – decimal or exponential float
%% – a literal %
A float:
>>> '%s' % 7.03 '7.03' >>> '%f' % 7.03 '7.030000' >>> '%e' % 7.03 '7.030000e+00' >>> '%g' % 7.03 '7.03'
An integer and a literal %:
>>> '%d%%' % 100 '100%'
Some string and integer interpolation:
>>> actor = 'Richard Gere' >>> cat = 'Chester' >>> weight = 28 >>> "My wife's favorite actor is %s" % actor "My wife's favorite actor is Richard Gere" >>> "Our cat %s weighs %s pounds" % (cat, weight) 'Our cat Chester weighs 28 pounds'
That %s inside the string means to interpolate a string. The number of % appearances in the string needs match the number of data items after the %.
Multiple data must be grouped into a tuple (bounded by parentheses, separated by commas) such as:
print("My wife's favorite actor is %s and his cat is %s,\ whose weight is %d" %(actor,cat,weight))
the output will be:
My wife's favorite actor is Richard Gere and his cat is Chester,whose weight is 28
You can add other values between the % and the type specifier to designate minimum and maximum widths, alignment, and character filling:
1. Set a minimum field width of 10 characters for each variable, and align them to the right, filling unused spots on the left with spaces.
>>> n = 42 >>> f = 7.03 >>> s = 'string cheese' >>>'%10d %10f %10s' % (n, f, s) ' 42 7.030000 string cheese'
2. Use the same field width, but align to the left (minus number):
>>> '%-10d %-10f %-10s' % (n, f, s) '42 7.030000 string cheese'
3. number after the decimal: It means maximum character number for the string, but means the number of digit after the decimal point for floating number . E.g. same field width(6), maximum character width of 2, and aligned to the right. This setting truncates the string, and limits the float to 2 digits after the decimal point:
Now we make the weight of the cat little bit of
actor='Richard Gere' cat='Chester' weight=28.121313 print("My wife's favorite actor is %s and his cat is %10.5s,whose weight is %8.2f" %(actor,cat,weight))
output:
My wife's favorite actor is Richard Gere and his cat is Chest,whose weight is 28.12
4. get the field widths from arguments rather than hard-coding them:
>>> '%*.*d %*.*f %*.*s' % (10, 4, n, 10, 4, f, 10, 4, s) ' 0042 7.0300 stri'
If we assign this string to the keyword parameter “sep” of the print function:
>>> q = 459 >>> p = 0.098 >>> print(q, p, p * q) 459 0.098 44.982 >>> print(q, p, p * q, sep=",") 459,0.098,44.982 >>> print(q, p, p * q, sep=" :-) ") 459 :-) 0.098 :-) 44.982
New style formatting with {} and format
The new format method was added in Python 2.6 , however the old format is still supported. The general form of this method looks like this:
template.format(p0, p1, ..., k0=v0, k1=v1, ...)
The template (or format string) is a string which contains one or more format codes (fields to be replaced) embedded in constant text. The “fields to be replaced” are surrounded by curly braces {}.
eg.
>>n=42 >>f=7.03 >>s='string cheese' >> '{} {} {}'.format(n, f, s) '42 7.03 string cheese'
1. With new-style, you can specify the order:
>> '{2} {0} {1}'.format(f, s, n) '42 7.03 string cheese'
2. The list of arguments starts with zero or more positional argument.
The arguments can be a dictionary or named arguments, and the specifiers can include their names:
>> '{n} {f} {s}'.format(n=42, f=7.03, s='string cheese') '42 7.03 string cheese'
3. Add a data temporarily, In the following example, {0} is the entire dictionary, whereas {1} is the string ‘other’ that follows the dictionary:
>> '{0[n]} {0[f]} {0[s]} {1}'.format(d, 'other') '42 7.03 string cheese other'
4. Specify the data type after a “:” .
To specify n as dicemal(d), f as floating(f), s as string data(s).
>> '{0:d} {1:f} {2:s}'.format(n, f, s) '42 7.030000 string cheese'
5. Similar to old style, add the number to specify the minimum field width, maximum character width, alignment:
Example:
6. The alignment expression is different :
Option | Meaning |
---|---|
< | The field will be left-aligned within the available space. This is usually the default for strings. |
> | The field will be right-aligned within the available space. This is the default for numbers. |
^ | Forces the field to be centered within the available space. |
0 | If the width field is preceded by a zero (‘0’) character, sign-aware zero-padding for numeric types will be enabled.
>>> x = 378 >>> print("The value is {:06d}".format(x)) The value is 000378 >>> x = -378 >>> print("The value is {:06d}".format(x)) The value is -00378 |
, | This option signals the use of a comma for a thousands separator.
>>> print("The value is {:,}".format(x)) The value is 78,962,324,245 >>> print("The value is {0:6,d}".format(x)) The value is 5,897,653,423 >>> x = 5897653423.89676 >>> print("The value is {0:12,.3f}".format(x)) The value is 5,897,653,423.897 |
'=' | 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. |
7. The final option is the fill character. If you want something other than spaces to pad your output fields, put it right after the :, before any alignment (<, >, ^) or width specifiers.
>> '{0:!^20s}'.format('BIG SALE') '!!!!!!BIG SALE!!!!!!'