print "%10s is a filename"%stringvar
which would print the contents right-justified in a 10 character field. What if you wanted left-justified?
Well, then you would replace %10s with %-10s. Obvious, huh?
You could take advantage of some of the useful methods that Python strings own such as:
- rjust - presents a number or string right-justified in a field of specified width (there is an ljust as well)
- centre - presents the number or string centered in a filed of the specified field width
- zfill - to present a number or string of a specified width padded out with zeroes as needed
print "%s is a filename"%stringvar.rjust(10)
Of course, this is only useful if you are writing to a plain text file or a terminal. What if you are writing an HTML output? You could use named parameters like this..
print "%(noddy)s is a filename of %(max_len)d characters"%(max_len, noddy)
Notice the parameters are the wrong way round in the format specifier compared to the parameter list?
This can make constructing long format strings simpler. You can take this a step further by providing a dictionary instead of a list of parameters, like this
my_dict ={ 'name':'/var/log/message', 'code':1}
print "Examining %(name)s returned code %(code)i" %my_dict