[Tutor] slightly updated version of same script [string formatting]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 11 Dec 2001 23:59:36 -0800 (PST)


On Wed, 12 Dec 2001, Kirk Bailey wrote:

> Here ya go. Took out the extra crof and the testing code with the type
> statement.
> 
> Now that I can get this working, I need to go play with DIGESTING
> incoming email and examining header information. Good thing I trapped a
> few incoming letters into files in the server so I have data to feed the
> script for testing.
> 
> Any and all, feel free to examine this and comment on anything you like.


One thing that might be good to point out is the thing you were wondering
about with CRLF:

> msg = "From: " + fromaddr + CRLF + "To: " + toaddrs + CRLF + "Subject: "
> + subject + CRLF


Python supports an interesting "string formatting" operation that makes
making 'msg' a little easier.  Here's an example of string formatting:


###
>>> template_message = """%s and %s     
... went down a %s  
... to fetch a %s."""      
>>> print template_message
%s and %s
went down a %s
to fetch a %s.
>>> msg1 = template_message % ('jack', 'jill', 'hill', 'bucket of water')
>>> print msg1
jack and jill
went down a hill
to fetch a bucket of water.
###

I've always thought of this as the "Madlibs" operator.  We can take a
string that has these '%s' placeholders, and plug in values.  msg1 is the
result.  Try it out; it's quite fun.


String formatting doesn't affect our template_message, so: we can use it
over and over:

###
>>> print template_message % ('bill', 'ted', 'phone booth', 'napoleon')
bill and ted
went down a phone booth
to fetch a napoleon.
###


Of course, it's good to see what happens if we give too many or too few
things to the formatting operator:

###
>>> print template_message % ('neo', 'trinity')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: not enough arguments for format string
>>> print template_message % ('neo', 'trinity', 'morpheus', 'cypher',
                              'switch', 'tank')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: not all arguments converted
###

so we can expect to see these kinds of error messages if we mishandle the
formatting operation a little.



We can use this formatting to make the msg construction a little less
messy:

###
msg_template = """From: %s
To: %s
Subject: %s
"""
msg = msg_template % (fromaddr, toaddrs, subject)
msg = msg.replace('\n', '\r\n')
###


The line right below the string formatting is a small trick to plug in
those pesky carriage returns, so that we don't clutter up the
msg_template.


Hope this helps!