Before the order

Preferably only one-obvious way to do it. ———— The Zen of Python translation: Python advocates one, and preferably only one, way to do something

Python does this, but it doesn’t do it with string formatting.

String formatting

There are at least three common ways to format strings in Python:

  1. %-formatting format (recommended for output before Python2.6)
  2. Str.format () format(Python2.6, recommended for string concatenation)
  3. F-string format (Python3.6, recommended)

Printf-style string formatting (%-formatting format)

This was the only way before Python2.6, using the same syntax as the printf function in C.

Basic syntax: Format % value (where format is a string), in which the % conversion marker is replaced with zero or more value entries

Basic usage

# coding in Python3.7
print('this is %s blog written in %d%%%02d%%%d %02d:%d:%06.2f' 
      % ('TinyDolphin'.2019.5.31.9.30.22.3333))
# this is TinyDolphin blog written in 2019%05%31 09:30:022.33

print('title=%(title)s, author=%(name)s' 
      % {'name': 'TinyDolphin'.'title': 'Python syntax: String formatting '})
# title=Python 语法浅析:字符串格式化, author=TinyDolphin

print('%0*.*f' % (6.2.2.345))
# 002.35
Copy the code

Printf grammar

For these conversion marker characters, the following order must be followed: % --> (name) -->The '#',The '-','0','+',' '-- > m.n | m - > d, s, r, f 2, common conversion type: % s format string (STR () function) % r formatted string (repr () function) % d % f formatting floating-point number, format the integer to specify the accuracy of three decimal places, transformation of common markup characters: - Left aligned + displays a plus sign (+) in front of a positive number# display zero before octal ('0') and either '0x' or '0x' before hexadecimal (depending on whether 'x' or 'x' is used)0 is padded before the number displayed'0'Instead of the default space %'% %'Output a singleThe '%'M.n indicates that m is the minimum total width to display, and n is the number of digits after the decimal point * Definition width or decimal precision (used when m.n cannot be specified in advance) (var) Mapping variable (dictionary argument)Copy the code

2, string format(str.format())

Python2.6 adds a string formatting function str.format(), which enhances string formatting functions, such as position mapping, keyword mapping, object attribute mapping, subscript mapping, and so on

The basic syntax is to replace the previous % with {} and:. For example, ‘%03.2f’ is rewritten to ‘{:03.2f}’.

Two formatting methods:

Str. format(*args, **kwargs) String formatting operation. STR contains a substitution field enclosed in the string literal AND {}. Str.format_map (mapping) is similar to str.foramt(**mapping) except that mapping is used directly instead of being copied to a dict.Copy the code

Format (value, format_spec) : converts to type(value). Format (value, format_spec)

Basic usage

1. Access parameters by position

'{0} {1} - {2}'.format('a'.'b'.'c')     # 'a-b-c'
'{} - {} - {}'.format('a'.'b'.'c')        # 'a-b-c'
'{2} {1} - {0}'.format('a'.'b'.'c')     # 'c-b-a'
'{2} {1} - {0}'.format(*'abc')            # 'c-b-a'

args = ['a'.'b'.'c']
'{2} {1} - {0}'.format(*args)             # 'c-b-a'

'{0} {1} - {0}'.format(*['abc'.'def'])   # 'abc-def-abc'
Copy the code

2. Access parameters by name

'{a}-{b}'.format(a='1', b='2')          1-2 '#'

kwargs = {'a':'1'.'b':'2'}
'{a}-{b}'.format(**kwargs)              1-2 '#'
Copy the code

3. Access the properties of the parameter

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(3.4))                        # 'Point(3, 4)'
Copy the code

4. Access the item of the parameter

point = (3.5)
'X:{0[0]} Y:{0[1]}'.format(point)       # 'X:3 Y:5'
Copy the code

5, replace %s and %r (! S,! R)

'str() = {! s}; repr() = {! r}'.format('a'.'a')  # "str() = a; repr() = 'a'"
Copy the code

6, Align the text and specify the width (:<, :^, :>)

'{: < 20}'.format('left aligned')         # 'left aligned '
'20} {: >'.format('right aligned')        # ' right aligned'
'20} {: ^'.format('centered')             # ' centered '
# use '*' as padding character
'20} {: * ^'.format('centered')            # '******centered******'
Copy the code

7, replace %+f, %-f, and %f and specify signs (:+, :-, 🙂

'{:+f} {:+f}'.format(3.14.3.14)       # '+3.140000 -3.140000'
'{: f} {: f}'.format(3.14.3.14)       # '3.140000-3.140000' + - > space
'{:-f} {:-f}'.format(3.14.3.14)       # '3.140000-3.140000' == '{:f} {:f}'
Copy the code

8, replace %x and %o and convert values based on different carry systems (:x, :d, :o, :b)

'int:{0:d} hex:{0:x} oct:{0:o} bin:{0:b}'.format(42)
# 'int:42 hex:2a oct:52 bin:101010'
'int:{0:d} hex:{0:#x} oct:{0:#o} bin:{0:#b}'.format(42)
# 'int:42 hex:0x2a oct:0o52 bin:0b101010'
#' #' : prefix: 0x, 0O, 0B
Copy the code

9, use comma as thousand separator (:,)

'{...},'.format(123456789)                # '123456789'
Copy the code

10. Expressed as a percentage (:.2%)

'{:.2%}'.format(19/22)                  # '86.36%'
Copy the code

11. Use a specific type of formatting

import datetime
d = datetime.datetime(2019.6.10.22.5.13)
'{:%Y-%m-%d %H:%M:%S}'.format(d)
# '2019-06-10 22:05:13'
Copy the code

Nested parameters and more complex examples

slightlyCopy the code

3, Format string literals (F-string format)

Is a string literal prefixed with ‘f’ or ‘f’.

Anything other than curly braces is treated as its literal value, except that double curly braces ‘{{‘ or ‘}}’ are replaced with corresponding single curly braces.

The syntax is as follows:

Single curly brace'{', indicating a replacement field (starting with a Python expression) + possibly one with an exclamation mark'! 'The conversion character + for the tag may have a colon':'Tag the format specifier + with a close curly brace'} 'As the end of theCopy the code

Note: Expressions in formatted string literals:

  • Treat it as a normal Python expression (this is important and powerful)
  • Empty expressions are not allowed
  • Lambda expressions must be explicitly parenthesized
  • Can include newlines (for example in a triple quoted string)
  • Cannot include comments
  • Evaluated from left to right

If a conversion is specified, the result of the expression evaluation is converted before formatting. This is then formatted using the built-in Python function format().

Basic usage

name = 'tinyDolphin' f'my name is {name}' # 'my name is tinyDolphin' f'my name is {name! R}' # "width = 10 precision = 4 value = 12.34567 f'{value:{width}.{precision}}' # ' today = datetime.datetime(year=2019, month=6, day=10) f'{today:%B %d, %Y}' # 'June 10, 2019' number = 1024 f'{number:#0x}' # '0x400'Copy the code

PS: Differs a little from str.format() : in str.format(), non-numeric indexes are automatically converted to strings, while f-strings are not.

kwargs = {'a':1.'b':2}
# use STR. The format ()
'a={kwargs[a]}'.format(kwargs=kwargs)   # 'a=1'

# use f - string
f"a={kwargs[a]}"                        # × An exception occurs
Traceback (most recent call last):
  File "<stdin>", line 1.in <module>
NameError: name 'a' is not defined

# Use f-string correctly
f"a={kwargs['a']}"                      # 'a=1'

Copy the code

conclusion

Comparison is made from the following three aspects:

F -string > str.format() > %-formatting > str.format() f-string > str.format() > %-formattingCopy the code

For speed verification, the author will not be verified here.

Recommended scenarios:

In Python2, str.format() is preferred for some operations involving output because of its performance advantages: in Python2, f-string is preferred for some operations involving string concatenation because of its functional advantages: Python3, highly recommendedCopy the code