Python string format operation - format method

The format() method is recommended

String operations for%, official and given this formatting operation is out of date and may disappear in future versions of Python. Use the new string format in the new code. So we recommend that you use format() to replace%

The format method is the system's ability to replace and format complex variables, so let's see what they are used for.

format()

This method is a method from the Formatter class of the string module, which belongs to a built-in method. Therefore, this method can be called in the category of string object.

Grammatical structure

This method is too powerful. The official user is.

replacement_field ::=  "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name        ::=  arg_name ("." attribute_name | "[" element_index "]")*
arg_name          ::=  [identifier | integer]
attribute_name    ::=  identifier
element_index     ::=  integer | index_string
index_string      ::=  <any source character except "]"> +
conversion        ::=  "r" | "s" | "a"
format_spec       ::=  <described in the next section>

The usage for format_spec is as follows

format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]
fill        ::=  <a character other than '}'>
align       ::=  "<" | ">" | "=" | "^"
sign        ::=  "+" | "-" | " "
width       ::=  integer
precision   ::=  integer
type        ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

Explain:

  • < force fields to align left in free space
  • >Force fields to right within free space
  • =Fill after symbol (if any) but before number
  • ^Force the farm to be at the center of free space

The common methods are as follows: the slot in the format() method includes not only the parameter sequence number, but also the format control information. At this point, the internal style of the slot is as follows:

{: }

"{" [[identifier | integer]("." identifier | "[" integer | index_string "]")*]["!" "r" | "s" | "a"] [":" format_spec] "}"

Among them, the format used to control the parameter display includes: 6 fields:: < 6 precision > 6. These fields are optional and can be used in combination. They are described as follows one by one.

Commonly used expressions

  • Designated location
>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c')  # 3.1+ only
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc')      # unpacking argument sequence
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad')   # arguments' indices can be repeated
'abracadabra'

If you want to display {}

>>> '{{}}, {}, {}'.format('b', 'c')
'{}, b, c'
  • Specified name
>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'
  • Specified attribute
    For complex numbers, there are two properties. If you don't know the specific name of the attribute, you can use dir to view it.
>>> c = 3-5j
>>> dir(c)
[....... 'imag', 'real']
>>> ('The complex number {0} is formed from the real part {0.real} '
...  'and the imaginary part {0.imag}.').format(c)
'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
>>> class Point:
...     def __init__(self, x, y):
...         self.x, self.y = x, y
...     def __str__(self):
...         return 'Point({self.x}, {self.y})'.format(self=self)
...
>>> str(Point(4, 2))
'Point(4, 2)'
  • Accessing arrays and so on
>>> coord = (3, 5)
>>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
'X: 3;  Y: 5'
  • s difference! r
>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"
  • align text

Center and left aligned text below

>>> '{:<30}'.format('left aligned')
'left aligned                  '
>>> '{:>30}'.format('right aligned')
'                 right aligned'
>>> '{:^30}'.format('centered')
'           centered           '
>>> '{:*^30}'.format('centered')  # use '*' as a fill char
'***********centered***********'
  • Specified type

b: Binary mode of output integer;
c: Output Unicode characters corresponding to integers;
d: Decimal mode of output integer;
o: Octal mode of output integer;
x: Output integer in lowercase hexadecimal;
10: Output integer in uppercase hexadecimal;

>>> '{:+f}; {:+f}'.format(3.14, -3.14)  # show it always
'+3.140000; -3.140000'
>>> '{: f}; {: f}'.format(3.14, -3.14)  # show a space for positive numbers
' 3.140000; -3.140000'
>>> '{:-f}; {:-f}'.format(3.14, -3.14)  # show only the minus -- same as '{:f}; {:f}'
'3.140000; -3.140000'
  • Comma as thousands of separators:
>>> '{:,}'.format(1234567890)
'1,234,567,890'
  • Percentage
>>> points = 19
>>> total = 22
>>> 'Correct answers: {:.2%}.'.format(points/total)
'Correct answers: 86.36%'
  • Specific formats, such as dates
>>> import datetime
>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2010-07-04 12:15:58'

Sao operation

It can be used to output a table, which is similar to the effect of the tripartite library prettytable

>>> width = 5
>>> for num in range(5,12):
...     for base in 'dXob': # 10 / 16 / 8 / 2 base
...         print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
...     print()
...
    5     5     5   101
    6     6     6   110
    7     7     7   111
    8     8    10  1000
    9     9    11  1001
   10     A    12  1010
   11     B    13  1011

Advanced usage - template string

If you are looking at the source code of Python language tools, you will find such a usage - template string, for example, there is such a usage in robot ﹐ init ﹐ py. Let's look at the example first.

from string import Template

errorMessageTemplate = Template("""$reason
RIDE depends on wx (wxPython). .....""")

....

print(errorMessageTemplate.substitute(reason="wxPython not found."))

If there is a problem, it will be printed

wxPython not found.
RIDE depends on wx (wxPython). .....

First, you need to import the Template to see what properties are in it

>>> from string import Template as t
>>> dir(t)
[.....'braceidpattern', 'delimiter', 'flags', 'idpattern', 'pattern', 'safe_substitute', 'substitute']

>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'


>>> d = dict(who='tim')
>>> Template('Give $who $100').substitute(d)
Traceback (most recent call last):
[...]
ValueError: Invalid placeholder in string: line 1, col 10


>>> Template('$who likes $what').substitute(d)
Traceback (most recent call last):
[...]
KeyError: 'what'
>>> Template('$who likes $what').safe_substitute(d)
'tim likes $what'

Related reading

https://stackoverflow.com/questions/5082452/string-formatting-vs-format

https://www.python.org/dev/peps/pep-3101

https://blog.csdn.net/i_chaoren/article/details/77922939

https://docs.python.org/release/3.1.5/library/stdtypes.html#old-string-formatting-operations

https://docs.python.org/release/3.1.5/library/string.html#string-formatting

Have you got a deep understanding of format. Hurry up and practice.

Hi,Sup, if you think I'm good at writing, you can do me a favor

1, I can focus on my official account "programmer convergence", sharing the Internet frontier technology everyday, and let your trivial time not boring. I heard that people who are concerned are getting better and better.

2. By the way, I'll encourage more people to read this article. Hee hee.

Tags: Python Attribute

Posted on Fri, 14 Feb 2020 07:53:01 -0500 by chet23