2.16 以指定列宽格式化字符串

问题

你有一些长字符串,想以指定的列宽将它们重新格式化。

解决方案

使用 textwrap 模块来格式化字符串的输出。比如,假如你有下列的长字符串:

  1. s = "Look into my eyes, look into my eyes, the eyes, the eyes, \
  2. the eyes, not around the eyes, don't look around the eyes, \
  3. look into my eyes, you're under."

下面演示使用 textwrap 格式化字符串的多种方式:

  1. >>> import textwrap
  2. >>> print(textwrap.fill(s, 70))
  3. Look into my eyes, look into my eyes, the eyes, the eyes, the eyes,
  4. not around the eyes, don't look around the eyes, look into my eyes,
  5. you're under.
  6.  
  7. >>> print(textwrap.fill(s, 40))
  8. Look into my eyes, look into my eyes,
  9. the eyes, the eyes, the eyes, not around
  10. the eyes, don't look around the eyes,
  11. look into my eyes, you're under.
  12.  
  13. >>> print(textwrap.fill(s, 40, initial_indent=' '))
  14. Look into my eyes, look into my
  15. eyes, the eyes, the eyes, the eyes, not
  16. around the eyes, don't look around the
  17. eyes, look into my eyes, you're under.
  18.  
  19. >>> print(textwrap.fill(s, 40, subsequent_indent=' '))
  20. Look into my eyes, look into my eyes,
  21. the eyes, the eyes, the eyes, not
  22. around the eyes, don't look around
  23. the eyes, look into my eyes, you're
  24. under.

讨论

textwrap 模块对于字符串打印是非常有用的,特别是当你希望输出自动匹配终端大小的时候。你可以使用 os.get_terminal_size() 方法来获取终端的大小尺寸。比如:

  1. >>> import os
  2. >>> os.get_terminal_size().columns
  3. 80
  4. >>>

fill() 方法接受一些其他可选参数来控制tab,语句结尾等。参阅 textwrap.TextWrapper文档 获取更多内容。

原文:

http://python3-cookbook.readthedocs.io/zh_CN/latest/c02/p16_reformat_text_to_fixed_number_columns.html