Python格式化、顯示顏色

顯示顏色

Print a string that starts a color/style, then the string, then end the color/style change with '\033[0m':html

print('\033[6;30;42m' + 'Success!' + '\033[0m')

這樣就能夠輸出 Success!python

顯示顏色格式:
\033[顯示方式;字體色;背景色m String \033[0mgit

-------------------------------------------
字體色     |       背景色     |      顏色描述
-------------------------------------------
30        |        40       |       黑色
31        |        41       |       紅色
32        |        42       |       綠色
33        |        43       |       黃色
34        |        44       |       藍色
35        |        45       |       紫紅色
36        |        46       |       青藍色
37        |        47       |       白色
-------------------------------------------
-------------------------------
顯示方式     |      效果
-------------------------------
0           |     終端默認設置
1           |     高亮顯示
4           |     使用下劃線
5           |     閃爍
7           |     反白顯示
8           |     不可見
-------------------------------

打印全部可用顏色:ide

 1 def print_format_table():
 2     """
 3     prints table of formatted text format options
 4     """
 5     for style in range(8):
 6         for fg in range(30, 38):
 7             s1 = ''
 8             for bg in range(40, 48):
 9                 fmt = ';'.join([str(style), str(fg), str(bg)])
10                 s1 += '\033[%sm %s \033[0m' % (fmt, fmt)
11             print(s1)
12         print('\n')
13 
14 
15 print_format_table()

格式化輸出

參考官方文檔: https://docs.python.org/3/library/string.html#formatstrings字體

語法格式spa

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>
format_spec     ::=  [[fill]align][sign][#][0][width][grouping_option][.precision][type]
fill            ::=  <any character>
align           ::=  "<" | ">" | "=" | "^"
sign            ::=  "+" | "-" | " "
width           ::=  integer
grouping_option ::=  "_" | ","
precision       ::=  integer
type            ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

示例

經過位置

>>> '{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'

 

經過關鍵字參數

>>> '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'

 

經過對象屬性

>>> c = 3-5j
>>> ('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)'

 

經過下標

>>> coord = (3, 5)
>>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
'X: 3;  Y: 5'

 

填充與對齊

填充常跟對齊一塊兒使用
^、<、>分別是居中、左對齊、右對齊,後面帶寬度
:號後面帶填充的字符,只能是一個字符,不指定的話默認是用空格填充code

1 '{:>8}'.format('189')
>>> '     189'
2 '{:0>8}'.format('189')
>>> '00000189'
3 '{:a>8}'.format('189')
>>> 'aaaaa189'
>>> '{:<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***********'
>>> for align, text in zip('<^>', ['left', 'center', 'right']):
...     '{0:{fill}{align}16}'.format(text, fill=align, align=align)
...
'left<<<<<<<<<<<<'
'^^^^^center^^^^^'
'>>>>>>>>>>>right'

 

精度與類型f

精度常跟類型f一塊兒使用orm

1 '{:.2f}'.format(321.33345)
>>> '321.33'

 

其餘

字母b、d、o、x分別是二進制、十進制、八進制、十六進制。htm

1 width = 5
2 for num in range(16):
3     for base in 'dXob':
4         print('\033[1;31m{0:{width}{base}}\033[0m'.format(num, base=base, width=width), end=' ')
5     print()
>>> # 高亮顯示紅色字體, 背景顏色默認.
    0     0     0     0 
    1     1     1     1 
    2     2     2    10 
    3     3     3    11 
    4     4     4   100 
    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 
   12     C    14  1100 
   13     D    15  1101 
   14     E    16  1110 
   15     F    17  1111 
相關文章
相關標籤/搜索