| [ Web Proxy ] |
| Viewing: https://wiki.python.org/moin/../python/platforms/../gui/../../python/archive/StringFormatting.html | [Back] [Original] |
Legacy Wiki Page
This page was migrated from the old MoinMoin-based wiki. Information may be outdated or no longer applicable. For current documentation, see python.org.
The section of the manual on String Formatting Operations is hidden in the section on Sequence types.
Tutorial on the new string formatting method format() in Python 3.0: Py3kStringFormatting
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().
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 trailing comma
but a space will get inserted between successive prints. One 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.
You can also print a backspace ('\b') to swallow the extra space. eg:
1 for i in range(10):
2 print '\b%d' % i,
3 # Prints: 0123456789
Unfortunately, this produces a mess if output is being directed to a file; its best to avoid printing the space if you dont want it.
I want to print out all member of sys, then what I need is
1 for member in dir(sys):
2 print "sys." + member, "->", repr(getattr(sys, member))
2026, Python Software Foundation
Made with Sphinx and Shibuya theme.
| Web Proxy Viewer | New URL | Original Page |