Format the string with the specified column width
problem
You have some long strings , Want to reformat them with the specified column width .
solution
Use textwrap Module to format the output of a string . such as , If you have the following long string :
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."
Let's use textwrap There are many ways to format strings :
>>> 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.
Discuss
textwrap Module is very useful for string printing , Especially when you want the output to automatically match the terminal size . You can use os.get terminal size() Method to get the size of the terminal . such as :
>>> import os
>>> os.get_terminal_size().columns
80
>>>
fill() Method accepts some other optional parameters to control tab, End of sentence, etc . Refer to the textwrap.TextWrapper file Get more .