AligningFormatting Strings


Aligning/Formatting Strings

print "Chapter " + str(x) + \     str(chapters[x]).rjust(15,'.') print "\nHex String: " + hexStr.upper().ljust(8,'0') print "Chapter %d %15s" % (x,str(chapters[x]))

One of the biggest advantages of the Python language is its capability to process and manipulate strings quickly and effectively. The native string type implements the rjust(width [, fill]) and ljust(width [, fill]) methods to quickly justify the text in a string a specific width to the right or left, respectively. The optional fill argument to the rjust and ljust methods will fill the space created by the justification with the specified character.

Another extremely useful part of Python's string management is the capability to create complex string formatting on the fly by creating a format string and passing arguments to that string using the % operator. This results in a new formatted string that can be used in a string assignment, passed as an argument, or used in a print statement.

chapters = {1:5, 2:46, 3:52, 4:87, 5:90} hexStr = "3f8" #Right justify print "Hex String: " + hexStr.upper().rjust(8,'0') print for x in chapters:     print "Chapter " + str(x) + \         str(chapters[x]).rjust(15,'.') #Left justify print "\nHex String: " + hexStr.upper().ljust(8,'0') #String format print for x in chapters:     print "Chapter %d %15s" % (x,str(chapters[x]))


format_str.py

Hex String: 000003F8 Chapter 1..............5 Chapter 2.............46 Chapter 3.............52 Chapter 4.............87 Chapter 5.............90 Hex String: 3F800000 Chapter 1               5 Chapter 2              46 Chapter 3              52 Chapter 4              87 Chapter 5              90


Output from format_str.py code



Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net