[Tutor] file operations and formatting

Gonçalo Rodrigues op73418@mail.telepac.pt
Mon Dec 16 18:48:02 2002


----- Original Message -----
From: "Scott Widney" <SWidney@ci.las-vegas.nv.us>
To: "'andy surany'" <mongo57a@comcast.net>; <tutor@python.org>
Sent: Monday, December 16, 2002 11:38 PM
Subject: RE: [Tutor] file operations and formatting


> > a=99.99 # a float
> > b='hello world'
> > file=open('junk.txt','w')
> >
> > What I want is to write a and b to junk.txt with a space in
> > between (I'm using file.write).
>
> ### Here's the short answer
> >>> a = 99.99
> >>> b = 'hello world'
> >>> fd = file('junk.txt', 'w')
> >>> fd.write("%f %s" % a, b)
>

You will get an error here since % has lower precedence than , so that
Python parses this as ("%f %s" % a), b. It should be

fd.write("%f %s" % (a, b))

> > I tried using a format to write, but that didn't work -
> > mostly because I think that I don't understand formatting
> > as well as I should. So does anyone have a good
> > reference/tutorial for formatting?
>
> You'll find the options and descriptions to use in formatting statements
in
> the Python Library Reference, section 2.2.6.2 String Formatting
Operations.
> Here's a shortcut:
>
> http://www.python.org/doc/current/lib/typesseq-strings.html#l2h-148
>
>
> Enjoy!
> Scott
>

All the best,
G. Rodrigues