"Python Cookbook" "String and Text" 13. Aligning the string

Source: Internet
Author: User

Problem: Formatting text in some sort of alignment

Solution:

1. For string: Ljust (), Rjust (), center () method

2, for any value, more general: Format () more content: Https://docs.python.org/3/library/string.html#formatspec

>>> text='Hello World'>>> Text.ljust (20)'Hello World'>>> Text.rjust (20)'Hello World'>>> Text.center (20)'Hello World'>>> Text.ljust (20,'=')'Hello world========='>>> Text.rjust (20,'*')'*********hello World'>>> Text.center (20,'+')'++++hello world+++++'>>>

Format ():

Format qualifier

It has a rich "format qualifier" (syntax is {} with:), such as:

Fill and align
Padding is used in conjunction with alignment
^, <, > center, Align Left, right, back with width
: The fill character after the number, only one character, not specified by default is filled with a space

Accuracy and type F
Accuracy is often used in conjunction with Type F

Other types
Mainly in the system, B, D, O, X are binary, decimal, octal, hexadecimal.

Use, the number can also be used to make the amount of thousands separator.

>>> Format (text,'>20')'Hello World'>>> Format (text,'<20')'Hello World'>>> Format (text,'^20')'Hello World'>>> Format (text,'*>20')#other padding characters that are extra empty can be specified before the alignment'*********hello World'>>> Format (text,'=<20')'Hello world========='>>> Format (text,'%^20')'%%%%hello world%%%%%'>>>#when multiple values are formatted, the formatting code code can be used in the format () method>>>'{: >10} {: >10}'. Format ('Hello',' World')'Hello World'
>>>‘{: >10} {:%^10}‘. Format(‘Hello' ,'World')' Hello%%world%%%'>>> '{: #<10} {:%^10} '. Format('Hello','World')'hello#####%%world%%% '                    >>>'{: <20}'. Format ('Hello World')'Hello World'>>>'{:* <20}'. Format ('Hello World')'Hello world*********'>>>'{: ^20}'. Format ('Hello World')'Hello World'>>>

"Python Cookbook" "String and Text" 13. Aligning the string

Related Article

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.