2.16 ä»¥æŒ‡å®šåˆ—å®½æ ¼å¼�化å—符串¶
问题¶
ä½ æœ‰ä¸€äº›é•¿å—符串,想以指定的列宽将它们é‡�æ–°æ ¼å¼�化。
解决方案¶
使用 textwrap 模å�—æ�¥æ ¼å¼�化å—符串的输出。比如,å�‡å¦‚ä½ æœ‰ä¸‹åˆ—çš„é•¿å—符串:
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 æ ¼å¼�化å—符串的多ç§�æ–¹å¼�:
>>> 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() 方法æ�¥èŽ·å�–终端的大å°�尺寸。比如:
>>> import os
>>> os.get_terminal_size().columns
80
>>>
fill() 方法接å�—一些其他å�¯é€‰å�‚æ•°æ�¥æŽ§åˆ¶tab,è¯å�¥ç»“å°¾ç‰ã€‚
�阅 textwrap.TextWrapper文档 获�更多内容。