[Tutor] How does formatted printing work?
Steven D'Aprano
steve at pearwood.info
Sun Jun 9 06:54:03 CEST 2013
On 09/06/13 08:10, Michael Sparks wrote:
> I believe it's % string interpolation where % formats strings
> I'm reading Practical Programming and I'm stuck on page 35, question 6. b)
> where:
> "___" % 34.5 => "3.45e+01"
Okay, this has nothing to do with printing. % string interpolation is independent of printing. It just creates a new string, which you can store in a variable:
new_str = old_str % 34.5
Of course, you can print the string if you want to, but you don't have to.
% string interpolation is based very closely on the same thing from the C programming language. It is based on "%" being a "magic character" -- when you call
some_string % one_or_more_arguments
Python will search some_string for codes starting with % and replace them with values from the given arguments.
The simplest code is %s which just inserts the value converted to a string:
py> print( "value = [%s]" % 22.5 )
value = [22.5]
Anything outside of the % codes remains unchanged.
There's not a lot to see there. %s formatting is pretty trivial. But we can start to see more of the power when you provide extra fields, like width:
py> print( "value = [%8s]" % 22.5 )
value = [ 22.5]
There are other codes. As well as %s that simply turns any value into a string, there are also:
%d value must be an integer
%x integer displayed as hexadecimal, using lowercase a...f
%X integer displayed as hexadecimal, using uppercase A...F
%f value is displayed as a floating point number
%g like %f, but with slightly different display
%G like %f and %g, but with yet another display
and others.
You can read all about it here:
http://docs.python.org/2/library/stdtypes.html#string-formatting-operations
Does that help? If you have any further concrete questions, please ask.
--
Steven
More information about the Tutor
mailing list