diff options
Diffstat (limited to 'Doc/tutorial/inputoutput.rst')
| -rw-r--r-- | Doc/tutorial/inputoutput.rst | 17 |
1 files changed, 13 insertions, 4 deletions
diff --git a/Doc/tutorial/inputoutput.rst b/Doc/tutorial/inputoutput.rst index 9352f40..0259749 100644 --- a/Doc/tutorial/inputoutput.rst +++ b/Doc/tutorial/inputoutput.rst @@ -123,11 +123,11 @@ with zeros. It understands about plus and minus signs:: Basic usage of the :meth:`str.format` method looks like this:: - >>> print 'We are the {0} who say "{1}!"'.format('knights', 'Ni') + >>> print 'We are the {} who say "{}!"'.format('knights', 'Ni') We are the knights who say "Ni!" The brackets and characters within them (called format fields) are replaced with -the objects passed into the :meth:`~str.format` method. The number in the +the objects passed into the :meth:`~str.format` method. A number in the brackets refers to the position of the object passed into the :meth:`~str.format` method. :: @@ -149,6 +149,15 @@ Positional and keyword arguments can be arbitrarily combined:: ... other='Georg') The story of Bill, Manfred, and Georg. +``'!s'`` (apply :func:`str`) and ``'!r'`` (apply :func:`repr`) can be used to +convert the value before it is formatted. :: + + >>> import math + >>> print 'The value of PI is approximately {}.'.format(math.pi) + The value of PI is approximately 3.14159265359. + >>> print 'The value of PI is approximately {!r}.'.format(math.pi) + The value of PI is approximately 3.141592653589793. + An optional ``':'`` and format specifier can follow the field name. This allows greater control over how the value is formatted. The following example truncates Pi to three places after the decimal. @@ -239,8 +248,8 @@ writing. The *mode* argument is optional; ``'r'`` will be assumed if it's omitted. On Windows, ``'b'`` appended to the mode opens the file in binary mode, so there -are also modes like ``'rb'``, ``'wb'``, and ``'r+b'``. Windows makes a -distinction between text and binary files; the end-of-line characters in text +are also modes like ``'rb'``, ``'wb'``, and ``'r+b'``. Python on Windows makes +a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it'll corrupt binary data like that in :file:`JPEG` or :file:`EXE` files. Be |
