@@ -37,16 +37,23 @@ printing space-separated values. There are several ways to format output.
37
37
* The :meth: `str.format ` method of strings requires more manual
38
38
effort. You'll still use ``{ `` and ``} `` to mark where a variable
39
39
will be substituted and can provide detailed formatting directives,
40
- but you'll also need to provide the information to be formatted.
40
+ but you'll also need to provide the information to be formatted. In the following code
41
+ block there are two examples of how to format variables:
42
+
41
43
42
44
::
43
45
44
46
>>> yes_votes = 42_572_654
45
- >>> no_votes = 43_132_495
46
- >>> percentage = yes_votes / (yes_votes + no_votes)
47
+ >>> total_votes = 85_705_149
48
+ >>> percentage = yes_votes / total_votes
47
49
>>> '{:-9} YES votes {:2.2%}'.format(yes_votes, percentage)
48
50
' 42572654 YES votes 49.67%'
49
51
52
+ Notice how the ``yes_votes `` are padded with spaces and a negative sign only for negative numbers.
53
+ The example also prints ``percentage `` multiplied by 100, with 2 decimal
54
+ places and followed by a percent sign (see :ref: `formatspec ` for details).
55
+
56
+
50
57
* Finally, you can do all the string handling yourself by using string slicing and
51
58
concatenation operations to create any layout you can imagine. The
52
59
string type has some methods that perform useful operations for padding
@@ -197,7 +204,12 @@ notation. ::
197
204
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
198
205
199
206
This is particularly useful in combination with the built-in function
200
- :func: `vars `, which returns a dictionary containing all local variables.
207
+ :func: `vars `, which returns a dictionary containing all local variables::
208
+
209
+ >>> table = {k: str(v) for k, v in vars().items()}
210
+ >>> message = " ".join([f'{k}: ' + '{' + k +'};' for k in table.keys()])
211
+ >>> print(message.format(**table))
212
+ __name__: __main__; __doc__: None; __package__: None; __loader__: ...
201
213
202
214
As an example, the following lines produce a tidily aligned
203
215
set of columns giving integers and their squares and cubes::
0 commit comments