Design

Sunday, October 24, 2010

String Formatting in Python

An easy way to combine strings with non strings is to use commas:
>>>>>> print 'The value of pi is often rounded to',3.14
The value of pi is often rounded to 3.14

But what if you want to create a website that welcomes guests by their name after he or she logs in? What if you are pulling information from a list or a dictionary? For personalization or multiple use functionality, we will be using string formatting. Below are the different format characters. There are a few others, but they aren't necessary.
%s   string
%d integers or decimals, but returns floor integer
%r anything that is not a string, converts object to a string
%f floating point, so we can control precision after decimal

Here is an example of using each of the formats:
>>> name='Anderson Silva'
>>> weight= 105 #integer
>>> height= 1.92 #decimal, but I only want 1.9 displayed
>>> home= 'Brazil' #string, watch what happens with %r
>>> fighter1='''%s
... Nationality: %r
... Weight: %d kg
... Height %.1f m''' % (name,home,weight,height) #in order
>>> print fighter1
Anderson Silva
Nationality: 'Brazil' #%r leaves quotes around strings
Weight: 105 kg
Height 1.9 m

Here is an example converting centimetres to inches
>>> def convert(cm):
... inches=cm*.39370
... print 'There are %.2f inches in %d centimetres' % (inches,cm)
...
>>> convert(10)
There are 3.94 inches in 10 centimetres
>>>#two places after decimal are shown
>>> convert(3.544445)
There are 1.40 inches in 3 centimetres

%f has a default to print six numbers after the decimal. By adding '.1', '.2', '.3', etc... between the '%' and 'f', you determine how many numbers are visible after the decimal. You can also add '+' or '-' before the '.x', such as showing a change
>>> print "Today's stock price changed %+.2f" % 1.4888
Today's stock price changed +1.49

No comments:

Post a Comment