| | |
string formatting specifications
The syntax of the
str.format() method described in the python 2.6 documentation looks both powerful and complex. The idea of this thread is to start a collection of nice formatting examples which will ease the task of mastering this function. Please post useful examples, and document them
rabbits = { "flopsy" : 1.0/3, "mopsy" : 576.0/7, "cotton tail": .76/5, "peter": 300000.0/37, } for name in sorted(rabbits): # 13 and 10 are field width, > means right align, # .4f means a float with 4 digits after '.' print("{name:13}:{score:>10.4f}".format(name=name, score=rabbits[name])) """my output ----> cotton tail : 0.1520 flopsy : 0.3333 mopsy : 82.2857 peter : 8108.1081 """
1
•
•
•
•
Same example with computed field's width:
python Syntax (Toggle Plain Text)
rabbits = { "flopsy" : 1.0/3, "mopsy" : 576.0/7, "cotton tail": .76/5, "peter": 300000.0/37, } nwidth = 1 + max(len(name) for name in rabbits) for name in sorted(rabbits): # the name field's width is passed as argument to format print("{name:{namewidth}}:{score:>10.4f}".format( name = name, score = rabbits[name], namewidth = nwidth)) """my output ----> cotton tail : 0.1520 flopsy : 0.3333 mopsy : 82.2857 peter : 8108.1081 """
Last edited by Gribouillis; Oct 22nd, 2009 at 4:06 pm.
1
•
•
•
•
The floating point precision can be passed as argument too
python Syntax (Toggle Plain Text)
rabbits = { "flopsy" : 1.0/3, "mopsy" : 576.0/7, "cotton tail": .76/5, "peter": 300000.0/37, } nwidth = 1 + max(len(name) for name in rabbits) for name in sorted(rabbits): # the floating point precision is passed as argument to format print("{name:{namewidth}}:{score:>10.{precision}f}".format( name = name, score = rabbits[name], namewidth = nwidth, precision = 2)) """my output ----> cotton tail : 0.15 flopsy : 0.33 mopsy : 82.29 peter : 8108.11 """
Last edited by Gribouillis; Oct 22nd, 2009 at 4:01 pm.
0
•
•
•
•
White space in the fields can be filled with a single character.
python Syntax (Toggle Plain Text)
rabbits = { "flopsy" : 1.0/3, "mopsy" : 576.0/7, "cotton tail": .76/5, "peter": 300000.0/37, } nwidth = 1 + max(len(name) for name in rabbits) for name in sorted(rabbits): # A single character can be used before the alignment sign (< ^ = or >) # to fill white space in each field. print("{name:{fill}<{namewidth}}{score:{fill}>20.{precision}f}".format( name = name, score = rabbits[name], namewidth = nwidth, precision = 2, fill="-")) """my output ----> cotton tail-----------------0.15 flopsy----------------------0.33 mopsy----------------------82.29 peter--------------------8108.11 """
Last edited by Gribouillis; Oct 22nd, 2009 at 4:52 pm.
0
•
•
•
•
For complex templates, we can use
functools.partial to set the value of some of the template's arguments. This results in a cleaner code python Syntax (Toggle Plain Text)
import functools rabbits = { "flopsy" : 1.0/3, "mopsy" : 576.0/7, "cotton tail": .76/5, "peter": 300000.0/37, } template = "{name:{fill}<{namewidth}}{score:{fill}>20.{precision}f}" nwidth = 1 + max(len(name) for name in rabbits) # The use of functools.partial allows us to give a value to a subset of # the template's arguments. rabbit_line = functools.partial(template.format, namewidth = nwidth, precision = 2, fill="-") for name in sorted(rabbits): print(rabbit_line(name = name, score = rabbits[name])) """my output ----> cotton tail-----------------0.15 flopsy----------------------0.33 mopsy----------------------82.29 peter--------------------8108.11 """
Last edited by Gribouillis; Oct 22nd, 2009 at 6:00 pm.
1
•
•
•
•
Access a dictionary directly ...
python Syntax (Toggle Plain Text)
# a food:price dictionary food_dict = { 'soymilk' : 3.69, 'butter' : 1.95, 'bread' : 2.19, 'cheese' : 4.39 } # pull one key item like 'bread' out of the dictionary print("Bread = ${bread:4.2f}".format(**food_dict)) # Bread = $2.19
0
•
•
•
•
Formatting specifications for datetime.datetime objects differ from the standard ones. They obey the rules of datetime.datetime.strftime. Each class can define its own formatting specifications through its __format__ method.
python Syntax (Toggle Plain Text)
from datetime import datetime import sys from os.path import getmtime python = sys.executable pytime = datetime.fromtimestamp(getmtime(python)) print("My python executable was last modified on {t:%b %d %Y} at {t:%H:%M:%S}." .format(t=pytime)) """my output ----> My python executable was last modified on Aug 22 2009 at 18:38:31. """
Last edited by Gribouillis; Oct 22nd, 2009 at 9:16 pm.
0
•
•
•
•
The different floating point formatting types (exponential, fixed, general, number and percentage).
Note that for large numbers, the exponential notation is superior. Also note that for the g and G type, the precision .2 is interpreted as a number of significant digits.
python Syntax (Toggle Plain Text)
from math import pi ftypes = "e E f F g G n %".split() header = "".join("{{types[{i}]:^10}}".format(i = i) for i in range(len(ftypes))) line = "".join("{{val:^10.2{tp}}}".format(tp = t) for t in ftypes) print(line) print('') print(header.format(types = ftypes)) print("-" * 80) for x in (pi*pi, 1.0/pi, pi **(-9), pi**17): print(line.format(val = x)) """ my output ----> {val:^10.2e}{val:^10.2E}{val:^10.2f}{val:^10.2F}{val:^10.2g}{val:^10.2G}{val:^10.2n}{val:^10.2%} e E f F g G n % -------------------------------------------------------------------------------- 9.87e+00 9.87E+00 9.87 9.87 9.9 9.9 9.9 986.96% 3.18e-01 3.18E-01 0.32 0.32 0.32 0.32 0.32 31.83% 3.35e-05 3.35E-05 0.00 0.00 3.4e-05 3.4E-05 3.4e-05 0.00% 2.83e+08 2.83E+08 282844563.59282844563.59 2.8e+08 2.8E+08 2.8e+08 28284456358.65% """
Last edited by Gribouillis; Oct 23rd, 2009 at 4:13 am.
0
•
•
•
•
For non numeric types, the precision is interpreted as a maximum field's width (the normal field's width is a minimum width).
python Syntax (Toggle Plain Text)
class Animal(): def __init__(self, name): self.name = name def __repr__(self): return "Animal({0})".format(self.name) animals = [ Animal(name) for name in "python lion giraffe antelope gnu".split() ] # Each field has a minimum width (10) and a maximum width (13). # The field's content is truncated if necessary. # this works only for non numeric fields. template = " | ".join("{{seq[{index}]:10.13}}".format(index = i) for i in range(len(animals))) print("template: " + template) print(template.format(seq = animals)) """ my output ----> template: {seq[0]:10.13} | {seq[1]:10.13} | {seq[2]:10.13} | {seq[3]:10.13} | {seq[4]:10.13} result: Animal(python | Animal(lion) | Animal(giraff | Animal(antelo | Animal(gnu) """
Last edited by Gribouillis; Oct 23rd, 2009 at 5:14 am.
0
•
•
•
•
Adding alignment and field widths capabilities. Since objects like datetime.datetime have their custom formatting syntax, they don't support alignment and field width capabilities.
For example, formatting a datetime with
Using the __format__ method, it's easy to write a general wrapper class Align which gives other objects the ability to handle alignment and field width in formatting operations.
The Align wrapper can be used for other kind of objects, and the decorator can be used to give the desired properties to user defined classes without the need to wrap the object in an Align wrapper.
For example, formatting a datetime with
{time:>20%H:%M:%S} won't cause the time to be right aligned in a field of length 20. Instead, the string >20 will be printed verbatim.Using the __format__ method, it's easy to write a general wrapper class Align which gives other objects the ability to handle alignment and field width in formatting operations.
python Syntax (Toggle Plain Text)
#!/usr/bin/env python from functools import update_wrapper import re _align_re =re .compile (r"^([<^>]?[0-9]*)(?:[.][0-9]*)?") def with_align (format_method ,maxwidth =True ): """Decorator for custom __format__ methods. Gives a __format__ method the ability to handle alignment character and field min width and max width with the syntax [align][minwidth].[maxwidth] similar to the standard formatting syntax """ def wrapper (self ,format_spec ): match =_align_re .match (format_spec ) index =match .end (0 if maxwidth else 1 ) match ,format_spec =format_spec [:index ],format_spec [index :] data_str =format_method (self ,format_spec ) if match : data_str =("{0:"+match +"}").format (data_str ) return data_str update_wrapper (wrapper ,format_method ) return wrapper class Align (object ): """Wrapper class to allow format alignment. Wrapping an object in Align adds alignment capabilities to the object in formatting operations. Example: "Time is {0:>10%H%M%S}".format(Align(datetime.now())) """ def __init__ (self ,wrapped_obj ): self .wrapped_obj =wrapped_obj @with_align def __format__ (self ,format_spec ): return ("{0:"+format_spec +"}").format (self .wrapped_obj ) def dtime (): "Returns a datetime object for testing purposes" from sys import executable as python from datetime import datetime from os .path import getmtime return datetime .fromtimestamp (getmtime (python )) def atest (): "Test of formatting a datetime object with alignment" print ("Test without Align:") # The alignment and field width can't be used for datetime print ("Time was: {time:>20%H:%M:%S}".format (time =dtime ())) # Wrapping the datetime object in an Align object allows # to handle the alignment specification print ("Test with Align:") print ("Time was: {time:>20%H:%M:%S}".format (time =Align (dtime ()))) atest () """ my output ----> Test without Align: Time was: >2018:38:31 Test with Align: Time was: 18:38:31 # correctly aligned """
Last edited by Gribouillis; Oct 23rd, 2009 at 4:52 pm.
Similar Threads
- String formatting (C#)
- VC++ bloody problem. What to use for string formatting (C++)
- String formatting using the "\t" character (Java)
- Date formatting? (Pascal and Delphi)
| Thread Tools | Search this Thread |
ada animation array assembly assign bluray c# c++ calculator challenge char character code convert count css data date datetime digital drawing drive dual dvd dynamic encryption exam exe file filename firefox format fstream ftp gdi+ getline hash hd html ide ifstream int introduction introductory java layer line list listbox memory method namevaluepairs parse parsing partition path perl professor proficiency program py py2exe python recursion regex retrieve reverse rotation search single slicenotation sony source string studio test time timer tutorial unicode university unreadable user validation video visual war wxpython year




