Differences between revisions 5 and 6
Revision 5 as of 2004-10-14 20:17:10
Size: 1495
Editor: rba-cache1-vif1
Comment:
Revision 6 as of 2004-10-14 20:18:22
Size: 1515
Editor: rba-cache1-vif1
Comment:
Deletions are marked like this. Additions are marked like this.
Line 45: Line 45:
#!python
Line 50: Line 51:
#!python

String Formatting

The [http://docs.python.org/lib/typesseq-strings.html section of the manual on String Formatting Operations] is hidden in the section on [http://docs.python.org/lib/typesseq.html Sequence types.]

Direct Variable Reference

A common trick you can use when writing strings is to refer directly to variables.

   1 a = "hello, world!"
   2 x = 34
   3 y = 96
   4 
   5 print """
   6 a = %(a)s
   7 x,y = (%(x)s,%(y)s)
   8 """ % vars() # local variables

If you want to refer to global variables, you can replace vars() with globals().

Printing Percentages

   1 percent = lambda x:"%2.2f%%" % x
   2 
   3 print percent(35.3567) # prints "35.35%"

You may find it tricky to print out a feed of numbers (as output from within a loop) on one line, without being separated by a space. An example could be output such as

Processing...
[1][2][3][4][5][6]
Completed.

The standard print statement automatically inserts newlines. This can be overcome with

   1 for i in range(10):
   2     print '['+str(i)+']',  # NOTE the trialing comma

but a space will get inserted between successive prints. The way to get around this is using sys.stdout:

   1 import sys
   2 for i in range(10):
   3     sys.stdout.write('['+str(i)+'[')

which will work properly.

See Also

EscapingHtml, WorkingWithTime

Discussion

(None yet!)

StringFormatting (last edited 2008-11-15 14:00:43 by localhost)

Unable to edit the page? See the FrontPage for instructions.