|
1 | | -============================ |
2 | | -2.16 格式化字符串为指定列宽 |
3 | | -============================ |
| 1 | +========================== |
| 2 | +2.16 以指定列宽格式化字符串 |
| 3 | +========================== |
4 | 4 |
|
5 | 5 | ---------- |
6 | 6 | 问题 |
7 | 7 | ---------- |
8 | | -todo... |
| 8 | +你有一些长字符串,想以指定的列宽将它们重新格式化。 |
| 9 | + |
| 10 | +| |
9 | 11 |
|
10 | 12 | ---------- |
11 | 13 | 解决方案 |
12 | 14 | ---------- |
13 | | -todo... |
| 15 | +Use the textwrap module to reformat text for output. For example, suppose you have |
| 16 | +the following long string: |
| 17 | +使用textwrap模块来格式化字符串的输出。比如,加入你有下列的长字符串: |
| 18 | + |
| 19 | +.. code-block:: python |
| 20 | +
|
| 21 | + s = "Look into my eyes, look into my eyes, the eyes, the eyes, \ |
| 22 | + the eyes, not around the eyes, don't look around the eyes, \ |
| 23 | + look into my eyes, you're under." |
| 24 | +
|
| 25 | +下面演示使用textwrap格式化字符串的多种方式: |
| 26 | + |
| 27 | +.. code-block:: python |
| 28 | +
|
| 29 | + >>> import textwrap |
| 30 | + >>> print(textwrap.fill(s, 70)) |
| 31 | + Look into my eyes, look into my eyes, the eyes, the eyes, the eyes, |
| 32 | + not around the eyes, don't look around the eyes, look into my eyes, |
| 33 | + you're under. |
| 34 | +
|
| 35 | + >>> print(textwrap.fill(s, 40)) |
| 36 | + Look into my eyes, look into my eyes, |
| 37 | + the eyes, the eyes, the eyes, not around |
| 38 | + the eyes, don't look around the eyes, |
| 39 | + look into my eyes, you're under. |
| 40 | +
|
| 41 | + >>> print(textwrap.fill(s, 40, initial_indent=' ')) |
| 42 | + Look into my eyes, look into my |
| 43 | + eyes, the eyes, the eyes, the eyes, not |
| 44 | + around the eyes, don't look around the |
| 45 | + eyes, look into my eyes, you're under. |
| 46 | +
|
| 47 | + >>> print(textwrap.fill(s, 40, subsequent_indent=' ')) |
| 48 | + Look into my eyes, look into my eyes, |
| 49 | + the eyes, the eyes, the eyes, not |
| 50 | + around the eyes, don't look around |
| 51 | + the eyes, look into my eyes, you're |
| 52 | + under. |
14 | 53 |
|
15 | 54 | ---------- |
16 | 55 | 讨论 |
17 | 56 | ---------- |
18 | | -todo... |
| 57 | +textwrap模块对于字符串打印是非常有用的,特别是当你希望输出自动匹配终端大小的时候。 |
| 58 | +你可以使用os.get_terminal_size()方法来获取终端的大小尺寸。比如: |
| 59 | + |
| 60 | +.. code-block:: python |
| 61 | +
|
| 62 | + >>> import os |
| 63 | + >>> os.get_terminal_size().columns |
| 64 | + 80 |
| 65 | + >>> |
| 66 | +
|
| 67 | +The fill() method has a few additional options that control how it handles tabs, sentence |
| 68 | +endings, and so on. Look at the documentation for the textwrap.TextWrapper |
| 69 | +class for further details. |
| 70 | + |
| 71 | +fill()方法接受一些其他可选参数来控制tab,语句结尾等。参阅 `textwrap.TextWrapper文档`_ 获取更多内容。 |
| 72 | + |
| 73 | +.. _textwrap.TextWrapper文档: |
| 74 | + https://docs.python.org/3.3/library/textwrap.html#textwrap.TextWrapper |
| 75 | + |
0 commit comments