Techniques of Practical Python 32: alignment of text strings

problem

We need to somehow do the alignment of the text formatting.

solution

The basic requirements for the alignment of the string, the string may be used ljust (), the rjust () and center () method. Examples are as follows:

>>> text = 'Hello World'
>>> text.ljust(20)
'Hello World '
>>> text.rjust(20)
'           Hello World'
>>> text.center(20)
'     Hello World '
>>>
Python资源分享qun 784758214 ,内有安装包,PDF,学习视频,这里是Python学习者的聚集地,零基础,进阶,都欢迎

All of these methods can accept an optional padding character. E.g:

>>> text.rjust(20,'=')
'=========Hello World'
>>> text.center(20,'*')
'****Hello World*****'
>>>

format () function can also be used to easily complete alignment tasks. Rational use to do is '<', '>' or '^' characters, and a desired width value [2]. E.g:

>>> format(text, '>20')
'           Hello World'
>>> format(text, '<20')
'Hello World '
>>> format(text, '^20')
'     Hello World '
>>>

If you want to contain the fill character other than spaces, can be specified before the alignment character:

>>> format(text, '=>20s')
'=========Hello World'
>>> format(text, '*^20s')
'****Hello World*****'
>>>

When formatting a plurality of values, which may be used in a format code format () method. E.g:

>>> '{:>10s} {:>10s}'.format('Hello', 'World')
'    Hello        World'
>>>

One of the advantages format () is that it is not specific to the string. It can act on any value, which makes it more versatile. For example, the digital format processing can be done:

>>> x = 1.2345
>>> format(x, '>10')
'     1.2345'
>>> format(x, '^10.2f')
'     1.23 '

discuss

In older code, operator will usually find% to format text. E.g:

>>> '%-20s' % text
'Hello World '
>>> '%20s' % text
'           Hello World'
Python资源分享qun 784758214 ,内有安装包,PDF,学习视频,这里是Python学习者的聚集地,零基础,进阶,都欢迎

But in the new code, we should be more in love with the format () function or method. format () operator than% stronger most of the functionality provided. In addition, the format () may be applied to any type of object, and the center () method to be more versatile than ljust string (), rjust ().

Guess you like

Origin blog.51cto.com/14445003/2430335
Recommended