"Python Cookbook" "String and Text" 16. Reformat text with a fixed number of columns

Source: Internet
Author: User

Problem: Reformat some very long strings to display in the specified number of columns

Solution: The Fill () method of the TextWrap module is used to implement

#A Long Strings ="Look to my eyes, look to my eyes, the eyes, the eyes, the eyes, not around the eyes, don ' t look around the eyes, l Ook into my eyes, you ' re under."ImportTextWrapPrint(Textwrap.fill (S, 70))Print()Print(Textwrap.fill (S, 40))Print()Print(s, Textwrap.fill, initial_indent='    ')) #Initial_indent: Adds the specified character display at the beginning of the first line. The default is blank. If the first row is a blank line, it is not added.Print()Print(s, Textwrap.fill, subsequent_indent='    ')) #Subsequent_indent: In addition to the first line, all other rows add the output of this string at the beginning of the row. The default is empty.
Print ()
>>> ================================ RESTART ================================>>>Look to my eyes, look into my eyes, the eyes, the eyes, the eyes, notAround the eyes, Don'T look around the eyes, look into my eyes,You're under.Look to my eyes, look into my eyes,the eyes, the eyes, the eyes, notaroundthe eyes, Don.'T look around the eyes,Look to my eyes, you're under.Look to my eyes, look into Myeyes, the eyes, the eyes, the eyes, notaround the eyes, Don'T look around theEyes, look to my eyes, you're under.Look to my eyes, look into my eyes, the eyes, the eyes, the eyes, notaround the eyes, Don'T Look aroundThe eyes, look to my eyes, you'Reunder.>>>

For the size of the terminal, it can be obtained by os.get_terminal_size ():

Import os>>> os.get_terminal_size (). Columns
80

The Fill () method also has additional options to control tabs, periods, and so on, see TextWrap. Document Https://docs.python.org/3.3/library/textwrap.html#textwrap.TextWrapper for the Textwrapper class

"Python Cookbook" "String and Text" 16. Reformat text with a fixed number of columns

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.