welcom ! Handel home

2016年5月4日 星期三

python print format demo

>>> print (" %3d %3d %4x" %(9,9,9))
   9   9    9
>>> print (" %3d %3d %04x" %(9,9,9))
   9   9 0009
>>> print (" %3d %3d %04x" %(9,9,12))
   9   9 000c
>>> print (" %03d %03d %04x" %(9,9,12))
 009 009 000c
>>> print (" %03d %05d %04x" %(9,9,12))
 009 00009 000c
>>> print (" %03d %05d %04x %s" %(9,9,12,"hello"))
 009 00009 000c hello
>>> 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
>>> 
General way of working of the string modulo operator


General way of working of the string modulo operator, format string 
The format string contains placeholders. There are two of those in our example: "%5d" and "%8.2f". 

>>> print("%10.3e"% (356.08977))
 3.561e+02
>>> print("%10.3E"% (356.08977))
 3.561E+02
>>> print("%10o"% (25))
        31
>>> print("%10.3o"% (25))
       031
>>> print("%10.5o"% (25))
     00031
>>> print("%5x"% (47))
   2f
>>> print("%5.4x"% (47))
 002f
>>> print("%5.4X"% (47))
 002F
>>> print("Only one percentage sign: %% " % ())
Only one percentage sign: % 
>>> 
>>> print("%#5X"% (47))
 0X2F
>>> print("%5X"% (47))
   2F
>>> print("%#5.4X"% (47))
0X002F
>>> print("%#5o"% (25))
 0o31
>>> print("%+d"% (42))
+42
>>> print("% d"% (42))
 42
>>> print("%+2d"% (42))
+42
>>> print("% 2d"% (42))
 42
>>> print("%2d"% (42))
42
>>> s = "Price: $ %8.2f"% (356.08977)
>>> print(s)
Price: $   356.09
>>>

General way of working of the format method with positional parameters

Examples of positional parameters:
>>> "First argument: {0}, second one: {1}".format(47,11) 
'First argument: 47, second one: 11'
>>> "Second argument: {1}, first one: {0}".format(47,11) 
'Second argument: 11, first one: 47'
>>> "Second argument: {1:3d}, first one: {0:7.2f}".format(47.42,11) 
'Second argument:  11, first one:   47.42'
>>> "First argument: {}, second one: {}".format(47,11) 
'First argument: 47, second one: 11'
>>> # arguments can be used more than once:
... 
>>> "various precions: {0:6.2f} or {0:6.3f}".format(1.4148) 
'various precions:   1.41 or  1.415'
>>> 
In the following example we demonstrate how keyword parameters can be used with the format method:
>>> "Art: {a:5d},  Price: {p:8.2f}".format(a=453, p=59.058)
'Art:   453,  Price:    59.06'
>>> 
General way of working of the format method with keyword parameters  It's possible to left or right justify data with the format method. To this end, we can precede the formatting with a "<" (left justify) or ">" (right justify). We demonstrate this with the following examples: 
>>> "{0:<20s 6.99="" amp="" eggs:="" f="" format="" pam="">>> "{0:>20s} {1:6.2f}".format('Spam & Eggs:', 6.99)
'        Spam & Eggs:   6.99'
>>> "{0:>20s} {1:6.2f}".format('Spam & Ham:', 7.99)
'         Spam & Ham:   7.99'
>>> "{0:<20s 7.99="" amp="" f="" format="" ham:="" pam="">>> "{0:<20 7.99="" amp="" f="" format="" ham:="" pam="">>> "{0:>20} {1:6.2f}".format('Spam & Ham:', 7.99)
'         Spam & Ham:   7.99'
>>> 
OptionMeaning
'<'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.
'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.
'^'Forces the field to be centered within the available space.
Unless a minimum field width is defined, the field width will always be the same size as the data to fill it, so that the alignment option has no meaning in this case.
Additionally, we can modify the formatting with the sign option, which is only valid for number types:
OptionMeaning
'+'indicates that a sign should be used for both positive as well as negative numbers.
'-'indicates that a sign should be used only for negative numbers, which is the default behavior.
spaceindicates that a leading space should be used on positive numbers, and a minus sign on negative numbers.

Using dictionaries in "format"

We have seen in the previous chapters that we have two ways to access the values to be formatted:
  • Using the position or the index:
    >>> print("The capital of {0:s} is {1:s}".format("Ontario","Toronto"))
    The capital of Ontario is Toronto
    >>> 
    
    Just to mention it once more: We could have used empty curly braces in the previous example!
  • Using keyword parameters:
    >>> print("The capital of {province} is {capital}".format(province="Ontario",capital="Toronto"))
    The capital of Ontario is Toronto
    >>>
    
The second case can be expressed with a dictionary as well, as we can see in the following code:
>>> print("The capital of {province} is {capital}".format(**k))
The capital of Ontario is Toronto
>>> 
Let's look at the following Python program:
capital_country = {"United States" : "Washington", 
                   "US" : "Washington", 
                   "Canada" : "Ottawa",
                   "Germany": "Berlin",
                   "France" : "Paris",
                   "England" : "London",
                   "UK" : "London",
                   "Switzerland" : "Bern",
                   "Austria" : "Vienna",
                   "Netherlands" : "Amsterdam"}

print("Countries and their capitals:")
for c in capital_country:
    print("{country}: {capital}".format(country=c, capital=capital_country[c]))
If we start this program, we get the following output:
$ python3 country_capitals.py 
Countries and their capitals:
United States: Washington
Canada: Ottawa
Austria: Vienna
Netherlands: Amsterdam
Germany: Berlin
UK: London
Switzerland: Bern
England: London
US: Washington
France: Paris
We can rewrite the previous example by using the dictionary directly. The output will be the same:
capital_country = {"United States" : "Washington", 
                   "US" : "Washington", 
                   "Canada" : "Ottawa",
                   "Germany": "Berlin",
                   "France" : "Paris",
                   "England" : "London",
                   "UK" : "London",
                   "Switzerland" : "Bern",
                   "Austria" : "Vienna",
                   "Netherlands" : "Amsterdam"}

print("Countries and their capitals:")
for c in capital_country:
    format_string = c + ": {" + c + "}" 
    print(format_string.format(**capital_country))

Using Local Variable Names in "format"

"locals" is a function, which returns a dictionary with the current scope's local variables, i.e- the local variable names are the keys of this dictionary and the corresponding values are the values of these variables:
>>> a = 42
>>> b = 47
>>> def f(): return 42
... 
>>> locals()
{'a': 42, 'b': 47, 'f': , '__builtins__': , '__package__': None, '__name__': '__main__', '__doc__': None}
>>> 
The dictionary returned by locals() can be used as a parameter of the string format method. This way we can use all the local variable names inside of a format string.  Continuing with the previous example, we can create the following output, in which we use the local variables a, b and f:
>>> print("a={a}, b={b} and f={f}".format(**locals()))
a=42, b=47 and f=

Other string methods for Formatting

The string class contains further methods, which can be used for formatting purposes as well: ljust, rjust, center and zfill  Let S be a string, the 4 methods are defined like this:
  • center(...):
    S.center(width[, fillchar]) -> str
    
    Return S centred in a string of length width. Padding is done using the specified fill character. The default value is a space.  Examples:
    >>> s = "Python"
    >>> s.center(10)
    '  Python  '
    >>> s.center(10,"*")
    '**Python**'
    
  • ljust(...):
     S.ljust(width[, fillchar]) -> str 
    
    Return S left-justified in a string of length "width". Padding is done using the specified fill character. If none is given, a space will be used as default.  Examples:
    >>> s = "Training"
    >>> s.ljust(12)
    'Training    '
    >>> s.ljust(12,":")
    'Training::::'
    >>> 
    
  • rjust(...):
    S.rjust(width[, fillchar]) -> str
    
    Return S right-justified in a string of length width. Padding is done using the specified fill character. The default value is again a space.  Examples:
    >>> s = "Programming"
    >>> s.rjust(15)
    '    Programming'
    >>> s.rjust(15, "~")
    '~~~~Programming'
    >>> 
    
  • zfill(...):
     
    S.zfill(width) -> str
    
    Pad a string S with zeros on the left, to fill a field of the specified width. The string S is never truncated. This method can be easily emulated with rjust.  Examples:
    >>> account_number = "43447879"
    >>> account_number.zfill(12)
    '000043447879'
    >>> # can be emulated with rjust:
    ... 
    >>> account_number.rjust(12,"0")
    '000043447879'
    >>> 
    

沒有留言: