[Tutor] how to insert a string?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Sep 23 01:51:29 CEST 2005



On Thu, 22 Sep 2005 andrade1 at umbc.edu wrote:

> I would like to insert a string into the following program to simplify
> the program. Any suggestions on how I might do so?

Hello,

It's a little unclear what you're asking when you mention "insert a
string": usually, inserting anything into a program makes it larger, and
consequently, slightly less simple.


Are you asking, instead, what techniques we can use to simplify the
program?  If so, one thing you may want to look at is the 'strftime'
function in the 'time' module.  For example:

######
>>> import time
>>> time.strftime("%B %d %Y")
'September 22 2005'
######

time.strftime() might not be perfect, since I think it only works on range
of dates starting from the Epoch (around 1970) to about the year 2038.
So if you need larger ranges than this, strftime probably won't be an
appropriate tool, although something like:

    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/306860

might be useful.



Anyway, let's take a quick at a line in your program.

>     date1 = str(month)+"/"+str(day)+"/"+str(year)

The construction of 'date1' can be slightly simplified if you use string
formatting:

    http://www.python.org/doc/lib/typesseq-strings.html


For example:

######
>>> "%s went up the hill" % ("curious george")
'curious george went up the hill'
######



Best of wishes!



More information about the Tutor mailing list