textwrap

我是从 hackrank 的 text wrap 题目了解到这个模块,稍微记录学下以下吧,挺方便的。

The textwrap module can be used for wrapping and formatting of plain text. textwrap 提供函数 wrap()fill()indent()dedent()和以及 TextWrapper 类。

如果只是要对一两个文本字符串进行自动换行或填充,直接用函数应该就够了;否则的话,应该使用 TextWrapper 的实例来提高效率。 这里只介绍常见的几个函数便于临时使用,如果需要深度使用,再去学。

  1. textwrap.wrap(text, width=70, **kwargs) Wraps the single paragraph in text (a string) so every line is at most width characters long. Returns a list of output lines, without final newlines.

    kwargs 参数, 可选,一般默认,与TextWrapper 类的属性有关。

    1
    2
    3
    4
    import textwrap
    In [26]: text = "helloworldthis isn't.."
    In [27]: textwrap.wrap(text, 5)
    Out[28]: ['hello', 'world', 'this ', "isn't", '..']

    注意:空格也算

  2. textwrap.fill(text, width=70, **kwargs) Wraps the single paragraph in text, and returns a single string containing the wrapped paragraph. fill() is shorthand for "\n".join(wrap(text, ...)), 根据指定长度拆分字符串,然后逐行显示。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    In [31]: textwrap.fill(text,5)
    Out[31]: "hello\nworld\nthis \nisn't\n.."

    In [32]: print(textwrap.fill(text,5))
    hello
    world
    this
    isn't
    ..

3.textwrap.indent(text, prefix, predicate=None) Add prefix to the beginning of selected lines in text. 在每行前面添加前缀 prefix

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
In [34]: text = """hello
...: world
...: this
...: is
...: a
...: """
In [35]: text
Out[35]: 'hello\nworld\nthis\nis\na\n'

In [37]: textwrap.indent(text, "---")
Out[37]: '---hello\n---world\n---this\n---is\n---a\n'

In [38]: print(textwrap.indent(text, "---"))
---hello
---world
---this
---is
---a

```

参考推荐:
[textwrap — Text wrapping and filling](https://docs.python.org/3/library/textwrap.html)