Files
Python_CookBook_repo/2.字符串和文本/16.以固定列数重新格式化文本.py
2025-09-10 16:12:45 +08:00

21 lines
918 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import textwrap
import os
if __name__ == '__main__':
words = ' '.join(["look", "into", "my", "eyes", "look", "into", "my", "eyes",
"the", "eyes", "the", "eyes", "the", "eyes", "not", "around", "the",
"eyes", "don't", "look", "around", "the", "eyes", "look", "into",
"my", "eyes", "you're", "under"])
print(words)
# 可以看到这样打印出来的字符串巨长无比如果想要控制行宽度就用textwrap模块
print(textwrap.fill(words, 70))
print(textwrap.fill(words, 40))
# 第二个参数width可以控制显示宽度如果是控制台输出你还能去找os.get_terminal_size()
# 注意由于未知原因这在pycharm中不好使2024.8.27
t_width = os.get_terminal_size().columns
print(t_width)
print(textwrap.fill(words, t_width))
# 用的应该不多在需要显示长字符串的时候去查textwrap库就行