06.0 Python‎ > ‎Python Notes‎ > ‎

Print using .format()

Very useful to neatly output your data. Only a small example is given here.
For more information see string python docs

The format method will automatically convert numeric data into string data.

Useful Python 3 tip:
# adding  , end="" in a print statement, will keep the cursor on the same line
# the next print statement will be on the same line
    print ("my first line", end="")
    print ("more of my first line")

.format() Syntax

"any_String".format(arguments)

any_String: any string containing {#} where # is the position of the argument in the arguments, starting with zero
arguments are separated by commas,
arguments can be  a variable, value or expression,
arguments can be thought of as parameters within a statement

flags:  Syntax 

The general form of a standard format specifier is:

format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]
fill        ::=  <any character>
align       ::=  "<" | ">" | "=" | "^"
sign        ::=  "+" | "-" | " "
width       ::=  integer
precision   ::=  integer
type        ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

This table is copied from:  https://docs.python.org/2/library/string.html
12/18/2014
These flags are contained within the {} after the #. A colon is added to separate the # from the flags.

[fill]
- any character

[align] Flags:
'^' - for center alignment
'<' - for left alignment 
'>' - for right alignment

[type] Flags:
'f' - float

Example #1: .format() in a print() statement 

Copy and paste this example and compare the output created. 
For a full explanation of the following example, please follow the link
""" from:  http://knowledgestockpile.blogspot.ca/2011/01/string-formatting-in-python_09.html
""" 12/16/2014

lang_info = [('Fortran', 1954, 0.435), ('Cobol', 1959, 0.391),
('C', 1972, 16.076), ('C++', 1980, 9.014),
('Python', 1991, 6.482),
('Java', 1995, 17.99), ('C#', 2001, 6.687)]

print ("Version #1 -- no formatting")
print ("Language Year Developed TIOBE rating")
print ("--------------------------------------")
for element in lang_info:
print (element[0], element[1], element[2])

print()
print ("Version #2 -- adding alignment")
print ("{0:12}{1:^16}{2:>16}".format("Language","Year Developed","TIOBE rating"))
print ("-"*46)
for element in lang_info:
print ("{0:12}{1:^16}{2:16}".format(element[0], element[1], element[2]))

print()
print ("Version #3 -- adding numeric precision -- 2 decimal places only for the rating")
print ("{0:12}{1:^16}{2:>16}".format("Language","Year Developed","TIOBE rating"))
print ("-"*46)
for element in lang_info:
print ("{0:12}{1:^16}{2:16.2f}".format(element[0], element[1], element[2]))


Example #2: .format() as a string modifier

Not only can .format()be used for format output, but .format() can be used return a modification of a string, 
#center the a string in 12 characters
str = "hello"
str = "{0:^12}".format(str)
print ("*"+str+"*")

#format a number with three decimals
# 4 must be used as it includes the decimal
pi= 3.141592
strPi = "{0:6.4}".format(pi)
print(strPi)

#format a float with three decimals
pi= 3.141592
strPi = "{0:6.3f}".format(pi)
print(strPi)

Example #3: .format() numbers

intNbr = 123456789
realNbr = 123456.789

print("Integer formatted with commas: {0:,}".format(intNbr))
print("Real formatted with commas: {0:,}".format(realNbr))
print("Real (float) formatted with commas and precision( 2 decimals): {0:10,.2f}".format(realNbr))
print("Real formatted with commas, precision and sign:{0:+20,.2f}".format(realNbr))
print("Real formatted with commas, precision sign and filled with -: {0:->+20,.2f}".format(realNbr))
print("Integer formatted with leading zeros: {0:020,}".format(intNbr))
print("Integer formatted with leading zeros: {0:0>20,}".format(intNbr))
Comments