========================== 2.16 ä»¥æŒ‡å®šåˆ—å®½æ ¼å¼åŒ–å—符串 ========================== ---------- 问题 ---------- ä½ æœ‰ä¸€äº›é•¿å—ç¬¦ä¸²ï¼Œæƒ³ä»¥æŒ‡å®šçš„åˆ—å®½å°†å®ƒä»¬é‡æ–°æ ¼å¼åŒ–。 ---------- 解决方案 ---------- 使用 ``textwrap`` æ¨¡å—æ¥æ ¼å¼åŒ–å—符串的输出。比如,å‡å¦‚ä½ æœ‰ä¸‹åˆ—çš„é•¿å—符串: .. code-block:: python s = "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." 䏋颿¼”示使用 ``textwrap`` æ ¼å¼åŒ–å—ç¬¦ä¸²çš„å¤šç§æ–¹å¼ï¼š .. code-block:: python >>> import textwrap >>> print(textwrap.fill(s, 70)) 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(textwrap.fill(s, 40)) 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(textwrap.fill(s, 40, initial_indent=' ')) 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(textwrap.fill(s, 40, subsequent_indent=' ')) 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. ---------- 讨论 ---------- ``textwrap`` 模å—对于å—ç¬¦ä¸²æ‰“å°æ˜¯éžå¸¸æœ‰ç”¨çš„ï¼Œç‰¹åˆ«æ˜¯å½“ä½ å¸Œæœ›è¾“å‡ºè‡ªåŠ¨åŒ¹é…终端大å°çš„æ—¶å€™ã€‚ ä½ å¯ä»¥ä½¿ç”¨ ``os.get_terminal_size()`` 方法æ¥èŽ·å–终端的大å°å°ºå¯¸ã€‚比如: .. code-block:: python >>> import os >>> os.get_terminal_size().columns 80 >>> ``fill()`` 方法接å—一些其他å¯é€‰å‚æ•°æ¥æŽ§åˆ¶tab,è¯å¥ç»“å°¾ç‰ã€‚ å‚阅 `textwrap.TextWrapper文档`_ èŽ·å–æ›´å¤šå†…容。 .. _textwrap.TextWrapper文档: https://docs.python.org/3.6/library/textwrap.html#textwrap.TextWrapper