| | |
string formatting specifications
Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
0
•
•
•
•
Partial formatting.
Normally, when you call format on a template string like
Using a subclass of string.Formatter, one can implement a partial formatting, with missing arguments. For example in the above example, we could instantiate first the precision to get the template
Normally, when you call format on a template string like
"{x:<15.{precision}e}{y:<15.{precision}e}" , all the template's arguments must be passed to format, otherwise, a KeyError is raised (or IndexError for positional arguments). Here we need to pass 3 keyword arguments x, y and precision.Using a subclass of string.Formatter, one can implement a partial formatting, with missing arguments. For example in the above example, we could instantiate first the precision to get the template
"{x:<15.3e}{y:<15.3e}" , and then format this string with a pair of values x and y. Here is the code python Syntax (Toggle Plain Text)
#!/usr/bin/env python from string import Formatter class MissingField (object ): "Helper class to implement partial formatting" def __init__ (self ,name ): self .name =name class MissingDict (dict ): "Helper class to implement partial formatting" def __missing__ (self ,key ): return MissingField (key ) class PartialFormatter (Formatter ): "Formatter class which allows missing keys in formatting" def format (self ,format_string ,*args ,**kwd ): return self .vformat (format_string ,args ,MissingDict (**kwd )) def format_field (self ,value ,format_string ): if isinstance (value ,MissingField ): s =":"+format_string if format_string else "" result ="{"+value .name +s +"}" else : result =Formatter .format_field (self ,value ,format_string ) return result def atest (): "Testing partial formatting" from math import sin template ="{x:<15.{precision}e}{y:<15.{precision}e}" print ("Initial template: "+template ) pf =PartialFormatter () ptemplate =pf .format (template ,precision =3 ) print ("Partial template: "+ptemplate ) print ("") for i in range (5 ): x =0.1 *i print (ptemplate .format (x =x ,y =sin (x ))) atest () """ my output ---> Initial template: {x:<15.{precision}e}{y:<15.{precision}e} Partial template: {x:<15.3e}{y:<15.3e} 0.000e+00 0.000e+00 1.000e-01 9.983e-02 2.000e-01 1.987e-01 3.000e-01 2.955e-01 4.000e-01 3.894e-01 """
Last edited by Gribouillis; Oct 24th, 2009 at 5:34 am.
0
•
•
•
•
Displaying tabular data
Here we use format to display tabular data. Consider reusing the Tabular class in your programs, as shown in the function 'test_func' below
Here we use format to display tabular data. Consider reusing the Tabular class in your programs, as shown in the function 'test_func' below
python Syntax (Toggle Plain Text)
#!/usr/bin/env python from os import linesep as LS class Tabular (object ): def __init__ (self ,columns ,gen_data ): """Create a Tabular object for formatting a table. @ columns is a sequence of triples (col_title, col_align, tpdata) - col_title is the string at the top of the column. It's width determines the column witdth - col align is "<" or "^" or ">" - tpdata is a template to format the column entries, with a single positional argument 0. @ gen_data is a generator of the table rows, which are tuples of values to be formatted. """ self .gen_data =gen_data columns =list (columns ) self .titles =[] self .templates =[] for col_title ,col_align ,tpdata in columns : tpcell ="{{0:{a}{w}.{w}}}".format (a =col_align ,w =len (col_title )) self .titles .append (col_title ) self .templates .append ((tpcell ,tpdata )) self .width =sum (len (x )for x in self .titles )+len (self .titles )-1 def delimit (self ,msg ): return "|"+msg +"|" def top (self ): return "-"*(self .width +2 ) bottom =top def lines (self ): yield self .top () yield self .delimit ("|".join (self .titles )) yield self .top () for line_data in self .gen_data : line =[] for (tpcell ,tpdata ),data in zip (self .templates ,line_data ): s =tpcell .format (tpdata .format (data )) line .append (s ) yield self .delimit ("|".join (line )) yield self .bottom () def __format__ (self ,format_spec ): if format_spec : template ="{0:"+format_spec +"}" return LS .join (template .format (line )for line in self .lines ()) else : return LS .join (self .lines ()) def test_func (): "Test the formatting of tables using Tabular" from math import sin dx =0.05 table =Tabular ( [("{0:^5}".format ("i"),"<"," {0}"), ("{0:^13}".format ("parameter"),"^","{0:.3e}"), ("{0:^20}".format ("value"),"^","{0:.3e}"),],# columns ((i ,i *dx ,sin (i *dx ))for i in range (5 ))# rows ) # formatting and printing the table # Look how the table is centered in a field of 72 characters. print "{ls}{title:^{width}}{ls}{tbl:^{width}}".format ( tbl =table ,title ="Table of sines.",width =72 ,ls =LS ) test_func () """ my output ---> Table of sines. ------------------------------------------ | i | parameter | value | ------------------------------------------ | 0 | 0.000e+00 | 0.000e+00 | | 1 | 5.000e-02 | 4.998e-02 | | 2 | 1.000e-01 | 9.983e-02 | | 3 | 1.500e-01 | 1.494e-01 | | 4 | 2.000e-01 | 1.987e-01 | ------------------------------------------ """
Last edited by Gribouillis; Oct 24th, 2009 at 10:57 pm.
0
•
•
•
•
Formatting with colors in a linux console
The following module combines formatting strings and ansi escape sequences to support printing with color in a linux console. After importing the module, type
The following module combines formatting strings and ansi escape sequences to support printing with color in a linux console. After importing the module, type
help(termstyle) for full documentation. python Syntax (Toggle Plain Text)
#!/usr/bin/env python # termstyle.py 0.9 (linux only) """This module implements a system using ANSI escape codes to display colors in a terminal. Example: from termstyle import Style, clear blue = Style("blue", "underline") clear() print( blue("Hello world")) print( "Velocity: {0:.3e} m/s" .format( blue(2.45589) )) """ CSI = "\x1b[" COLORS = "black red green yellow blue magenta cyan white".split() M_DICT = dict((w, str(30 + i)) for (i, w) in enumerate(COLORS)) # foreground colors M_DICT.update(("-" + w, str(40 + i)) for (i, w) in enumerate(COLORS)) # background colors EFFECTS = """ reset bold faint italic underline slow fast negative conceal crossout normal underlineoff blinkoff positive reveal """ .strip().split() M_DICT.update((w, str(i)) for i, w in enumerate(EFFECTS)) __all__ = ["Style", "clear"] class Style(object): """Style(*effects) --> a new Style object. @ effects is a sequence of -words like "red" (call Style.effects() to see all the words) -pairs (line, column) describing a terminal position -other Style objets * If 'effects' contains a Style instance, other effects are ignored and a copy of the first instance met is built. * If effects contains position pairs, only the last pair is used. * Call Style.colors() to see all foreground colors. * A background color is passed by putting "-" at the beginning of the color name. For example "-white" Effects can be disabled for all Styles, or for a Style instance by setting: Style.enable = False instance.enable = False """ enable = True @classmethod def effects(cls): "return an iterator over all possible named effects." return iter(M_DICT) @classmethod def colors(cls): "return an iterator over all foreground colors." return iter(COLORS) def __init__(self, *effects): "see class documentation" self.template = self.ansi_template(effects) def ansi_template(self, effects): "builds an ANSI template string from the sequence of effects" controls = [] position = "" for a in effects: if isinstance(a, Style): return a.template elif isinstance(a, tuple): line, column = (str(int(x)) for x in a) position = ''.join((CSI, line, ";", column, "H")) else: controls.append(M_DICT[a]) if controls: template = ''.join( (position, CSI, ';'.join(controls), "m", "{text}", CSI, "0m")) else: template = ''.join((position, "{text}")) if position: template = ''.join((CSI, "s", template, CSI, "u")) return template def __call__(self, content): """Calling a Style instance creates a StyledContent instance which can be printed in a terminal. If self.enable is False, content is returned instead""" return StyledContent(self, content) if self.enable else content class StyledContent(object): """StyleContent(style, content) --> a StyleContent instance. This is the type returned by Style.__call__. """ def __init__(self, style, content): "See class documentation" self.content = content self.style = style def __format__(self, format_spec): """Formatting a StyleContent instance is equivalent to formatting the content, with ANSI escape sequences added for terminal output""" return self.style.template.format( text = ("{0:" + format_spec + "}").format(self.content)) def __str__(self): """Calling str() on a StyleContent instance is equivalent to calling str() on the content, with ANSI escape sequences added for terminal output""" return self.style.template.format(text = self.content) def clear(): "clear the teminal" print(CSI + "2J") if __name__ == "__main__": def test_code(): "test function for module termstyle" from datetime import datetime from math import cos green = Style("-white", "green", "underline") blue = Style("blue", "bold") yellow = Style("yellow") cyan = Style("cyan") middle = Style((10, 20)) clear() print( "The current time is {0:%H:%M:%S}.".format(blue(datetime.now()))) print("") for i in range(5): x = 0.1 * i print("{0:12.3e}{1:12.3e}".format(yellow(x), cyan(cos(x)))) print( middle("This is a {w} of terminal styles." .format( w = green("test")))) test_code() """ my output (without the colors) ---> This is a test of terminal styles. The current time is 16:18:01. 0.000e+00 1.000e+00 1.000e-01 9.950e-01 2.000e-01 9.801e-01 3.000e-01 9.553e-01 4.000e-01 9.211e-01 """
Last edited by Gribouillis; Oct 27th, 2009 at 12:37 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 |
Tag cloud for format, string
2d access ada array assembly assign binary bluray bmp c# c++ calculator challenge char character code convert count css date datetime digital drawing drive dual dvd dynamic encryption exam exe file firefox format fstream ftp function gdi+ getline hash hd html ide ifstream image input int introduction java jpeg layer line list listbox loop memory method namevaluepairs parse parsing partition path pattern perl php professor proficiency program py py2exe python recursion regex retrieve reverse rotation saving search single slicenotation sony source sql string studio subscript superscript test time timer tutorial unicode university unreadable user validation video visual war wxpython year



