Python format string format

Author: Tyan
Blog:  |  CSDN  |  A brief book

0. Test environment

Python 3.6.9

1. Introduction

There are two ways to format strings in Python: one is to format strings with the% operator, and the other is to use the str.format() for string formatting, this article mainly introduces str.format() mode, which is more mainstream and also recommended by the government, will be gradually eliminated later.

2. Format string

2.1 basic grammar

The format string contains the replace field, enclosed in braces {},. Content not contained in braces is treated as normal text and output as is. Note: if you want to output braces in the text, you need to use {{and}} to escape, not the escape character \, of the scene. An example is as follows:

>>> 'This is a format {}.'.format('test')
'This is a format test.'
>>> 'This is {{}} test.'.format()
'This is {} test.'

The following is the syntax of "replace field", which will be described in the following examples:

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

2.2 location parameter identifier

In the format string, by default, {} can be without location identifier, that is, '{} {}'. format(a, b) and '{0} {1}'.format(a, b) are equivalent, but if the location identifier does not appear in the string in the order of parameters, it is necessary to display the location identifier. The sample code is as follows:

>>> '{0} {1}'.format('one', 'two')
'one two'
>>> '{} {}'.format('one', 'two')
'one two'
>>> '{1} {0}'.format('one', 'two')
'two one'
>>> '{0} {1} {0}'.format('one', 'two')
'one two one'

2.3 setting parameters

In the format string, you can use variables, dictionaries, list indexes, class properties, etc. to set parameters. The sample code is as follows:

print('Name: {name}, URL: {url}'.format(name='Tyan', url=''))

name = 'Tyan'
url = ''
print('Name: {}, URL: {}'.format(name, url))

site = {'name' : 'Tyan', 'url' : ''}
print('Name: {site[name]}, URL: {site[url]}'.format(site=site))
print('Name: {name}, URL: {url}'.format(**site))

site = ['Tyan', '']
print('Name: {0[0]}, URL: {0[1]}'.format(site))

class Test(object):
    def __init__(self): = 'Tyan'
        self.url = ''

print('Name: {}, URL: {0.url}'.format(Test()))

site = {'name' : 'Tyan', 'url' : ''}
print('Name: {name}, URL: {url}'.format(**site))

# Output
Name: Tyan, URL:
Name: Tyan, URL:
Name: Tyan, URL:
Name: Tyan, URL:
Name: Tyan, URL:
Name: Tyan, URL:
Name: Tyan, URL:

2.3 conversion flag

The conversion flag starts with! And there are three types of! s,! r,! a, which call the__ str__ ,__ repr__ ,__ ascii__ method.

class Test(object):

    def __str__(self):
        return 'Test str function.'

    def __repr__(self):
        return 'Test repr function.'

    def __ascii__(self):
        return 'Test ascii function.'

print('str: {t!s}, repr: {t!r}, ascii: {t!a}'.format(t=Test()))

# Ouput
str: Test str function., repr: Test repr function., ascii: Test repr function.

2.4 format_spec)

The format description contains the description of the value representation, including the field width, its method, filling, decimal accuracy, etc., which starts with. The general form of the standard format specifier is:

format_spec     ::=  [[fill]align][sign][#][0][width][grouping_option][.precision][type]
fill            ::=  <any character>
align           ::=  "<" | ">" | "=" | "^"
sign            ::=  "+" | "-" | " "
width           ::=  digit+
grouping_option ::=  "_" | ","
precision       ::=  digit+
type            ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
  • < indicates left alignment of output, > indicates right alignment, ^ indicates center alignment, = indicates that the fill value precedes the number after the symbol, for example, + 00001234.
  • +Indicates that both positive and negative numbers need to be signed, - indicates that only negative numbers need to be signed with a negative sign, indicates that a positive number is preceded by a space, and a negative number is preceded by a negative sign.
  • Digital representation. b represents binary format, c represents converting integer to character, D represents decimal integer, o represents octal format, x, X represents hexadecimal format, letters with x greater than 9 are lowercase, and letters with x greater than 9 are uppercase. The default is d.
  • Refer to document [1] for specific explanations of other descriptors.

Examples and results are as follows:



print('{:+f}; {:+f}'.format(3.14, -3.14))
print('{: f}; {: f}'.format(3.14, -3.14))
print('{:-f}; {:-f}'.format(3.14, -3.14))

print('int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}'.format(100))
print('int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}'.format(100))



print('percentage: {:.2%}'.format(1 / 3))

import datetime
print('{:%Y-%m-%d %H:%M:%S}'.format(

# Output
+3.140000; -3.140000
 3.140000; -3.140000
3.140000; -3.140000
int: 100;  hex: 64;  oct: 144;  bin: 1100100
int: 100;  hex: 0x64;  oct: 0o144;  bin: 0b1100100
percentage: 33.33%
2020-06-18 19:36:38






Tags: Python ascii Programming

Posted on Fri, 19 Jun 2020 05:15:58 -0400 by biodrux