Changeset 391 for python/trunk/Doc/tutorial/inputoutput.rst
- Timestamp:
- Mar 19, 2014, 11:31:01 PM (11 years ago)
- Location:
- python/trunk
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
python/trunk
-
Property svn:mergeinfo
set to
/python/vendor/Python-2.7.6 merged eligible /python/vendor/current merged eligible
-
Property svn:mergeinfo
set to
-
python/trunk/Doc/tutorial/inputoutput.rst
r2 r391 20 20 See the Library Reference for more information on this.) 21 21 22 .. index:: module: string23 24 22 Often you'll want more control over the formatting of your output than simply 25 23 printing space-separated values. There are two ways to format your output; the 26 24 first way is to do all the string handling yourself; using string slicing and 27 25 concatenation operations you can create any layout you can imagine. The 28 st andard module :mod:`string` contains someuseful operations for padding26 string types have some methods that perform useful operations for padding 29 27 strings to a given column width; these will be discussed shortly. The second 30 28 way is to use the :meth:`str.format` method. 29 30 The :mod:`string` module contains a :class:`~string.Template` class which offers 31 yet another way to substitute values into strings. 31 32 32 33 One question remains, of course: how do you convert values to strings? Luckily, … … 37 38 fairly human-readable, while :func:`repr` is meant to generate representations 38 39 which can be read by the interpreter (or will force a :exc:`SyntaxError` if 39 there is no tequivalent syntax). For objects which don't have a particular40 there is no equivalent syntax). For objects which don't have a particular 40 41 representation for human consumption, :func:`str` will return the same value as 41 42 :func:`repr`. Many values, such as numbers or structures like lists and … … 50 51 >>> repr(s) 51 52 "'Hello, world.'" 52 >>> str( 0.1)53 '0.1 '54 >>> repr( 0.1)55 '0.1 0000000000000001'53 >>> str(1.0/7.0) 54 '0.142857142857' 55 >>> repr(1.0/7.0) 56 '0.14285714285714285' 56 57 >>> x = 10 * 3.25 57 58 >>> y = 200 * 200 … … 103 104 way :keyword:`print` works: it always adds spaces between its arguments.) 104 105 105 This example demonstrates the :meth:`rjust` method of string objects, which 106 right-justifies a string in a field of a given width by padding it with spaces 107 on the left. There are similar methods :meth:`ljust` and :meth:`center`. These 108 methods do not write anything, they just return a new string. If the input 109 string is too long, they don't truncate it, but return it unchanged; this will 110 mess up your column lay-out but that's usually better than the alternative, 111 which would be lying about a value. (If you really want truncation you can 112 always add a slice operation, as in ``x.ljust(n)[:n]``.) 113 114 There is another method, :meth:`zfill`, which pads a numeric string on the left 115 with zeros. It understands about plus and minus signs:: 106 This example demonstrates the :meth:`str.rjust` method of string 107 objects, which right-justifies a string in a field of a given width by padding 108 it with spaces on the left. There are similar methods :meth:`str.ljust` and 109 :meth:`str.center`. These methods do not write anything, they just return a 110 new string. If the input string is too long, they don't truncate it, but 111 return it unchanged; this will mess up your column lay-out but that's usually 112 better than the alternative, which would be lying about a value. (If you 113 really want truncation you can always add a slice operation, as in 114 ``x.ljust(n)[:n]``.) 115 116 There is another method, :meth:`str.zfill`, which pads a numeric string on the 117 left with zeros. It understands about plus and minus signs:: 116 118 117 119 >>> '12'.zfill(5) … … 124 126 Basic usage of the :meth:`str.format` method looks like this:: 125 127 126 >>> print 'We are the { 0} who say "{1}!"'.format('knights', 'Ni')128 >>> print 'We are the {} who say "{}!"'.format('knights', 'Ni') 127 129 We are the knights who say "Ni!" 128 130 129 131 The brackets and characters within them (called format fields) are replaced with 130 the objects passed into the :meth:` ~str.format` method. A number in the132 the objects passed into the :meth:`str.format` method. A number in the 131 133 brackets refers to the position of the object passed into the 132 :meth:` ~str.format` method. ::134 :meth:`str.format` method. :: 133 135 134 136 >>> print '{0} and {1}'.format('spam', 'eggs') … … 137 139 eggs and spam 138 140 139 If keyword arguments are used in the :meth:` ~str.format` method, their values141 If keyword arguments are used in the :meth:`str.format` method, their values 140 142 are referred to by using the name of the argument. :: 141 143 … … 154 156 155 157 >>> import math 156 >>> print 'The value of PI is approximately { 0}.'.format(math.pi)158 >>> print 'The value of PI is approximately {}.'.format(math.pi) 157 159 The value of PI is approximately 3.14159265359. 158 >>> print 'The value of PI is approximately { 0!r}.'.format(math.pi)160 >>> print 'The value of PI is approximately {!r}.'.format(math.pi) 159 161 The value of PI is approximately 3.141592653589793. 160 162 161 163 An optional ``':'`` and format specifier can follow the field name. This allows 162 164 greater control over how the value is formatted. The following example 163 truncates Pi to three places after the decimal.165 rounds Pi to three places after the decimal. 164 166 165 167 >>> import math … … 195 197 Jack: 4098; Sjoerd: 4127; Dcab: 8637678 196 198 197 This is particularly useful in combination with the new built-in :func:`vars`198 function, which returns a dictionary containing all local variables.199 This is particularly useful in combination with the built-in function 200 :func:`vars`, which returns a dictionary containing all local variables. 199 201 200 202 For a complete overview of string formatting with :meth:`str.format`, see … … 206 208 207 209 The ``%`` operator can also be used for string formatting. It interprets the 208 left argument much like a :c func:`sprintf`\ -style format string to be applied210 left argument much like a :c:func:`sprintf`\ -style format string to be applied 209 211 to the right argument, and returns the string resulting from this formatting 210 212 operation. For example:: … … 214 216 The value of PI is approximately 3.142. 215 217 216 Since :meth:`str.format` is quite new, a lot of Python code still uses the ``%``217 operator. However, because this old style of formatting will eventually be218 removed from the language, :meth:`str.format` should generally be used.219 220 218 More information can be found in the :ref:`string-formatting` section. 221 219 … … 235 233 :: 236 234 237 >>> f = open(' /tmp/workfile', 'w')235 >>> f = open('workfile', 'w') 238 236 >>> print f 239 <open file ' /tmp/workfile', mode 'w' at 80a0960>237 <open file 'workfile', mode 'w' at 80a0960> 240 238 241 239 The first argument is a string containing the filename. The second argument is … … 294 292 '' 295 293 296 ``f.readlines()`` returns a list containing all the lines of data in the file. 297 If given an optional parameter *sizehint*, it reads that many bytes from the 298 file and enough more to complete a line, and returns the lines from that. This 299 is often used to allow efficient reading of a large file by lines, but without 300 having to load the entire file in memory. Only complete lines will be returned. 301 :: 302 303 >>> f.readlines() 304 ['This is the first line of the file.\n', 'Second line of the file\n'] 305 306 An alternative approach to reading lines is to loop over the file object. This is 307 memory efficient, fast, and leads to simpler code:: 294 For reading lines from a file, you can loop over the file object. This is memory 295 efficient, fast, and leads to simple code:: 308 296 309 297 >>> for line in f: … … 313 301 Second line of the file 314 302 315 The alternative approach is simpler but does not provide as fine-grained 316 control. Since the two approaches manage line buffering differently, they 317 should not be mixed. 303 If you want to read all the lines of a file in a list you can also use 304 ``list(f)`` or ``f.readlines()``. 318 305 319 306 ``f.write(string)`` writes the contents of *string* to the file, returning … … 338 325 beginning of the file as the reference point. :: 339 326 340 >>> f = open(' /tmp/workfile', 'r+')327 >>> f = open('workfile', 'r+') 341 328 >>> f.write('0123456789abcdef') 342 329 >>> f.seek(5) # Go to the 6th byte in the file … … 362 349 shorter than writing equivalent :keyword:`try`\ -\ :keyword:`finally` blocks:: 363 350 364 >>> with open(' /tmp/workfile', 'r') as f:351 >>> with open('workfile', 'r') as f: 365 352 ... read_data = f.read() 366 353 >>> f.closed
Note:
See TracChangeset
for help on using the changeset viewer.