Python格式化、显示颜色

显示颜色

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

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

这样就可以输出 Success!

显示颜色格式:
\033[显示方式;字体色;背景色m String \033[0m

-------------------------------------------
字体色     |       背景色     |      颜色描述
-------------------------------------------
30        |        40       |       黑色
31        |        41       |       红色
32        |        42       |       绿色
33        |        43       |       黃色
34        |        44       |       蓝色
35        |        45       |       紫红色
36        |        46       |       青蓝色
37        |        47       |       白色
-------------------------------------------
-------------------------------
显示方式     |      效果
-------------------------------
0           |     终端默认设置
1           |     高亮显示
4           |     使用下划线
5           |     闪烁
7           |     反白显示
8           |     不可见
-------------------------------

打印所有可用颜色:

 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

语法格式

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'

 

填充与对齐

填充常跟对齐一起使用
^、<、>分别是居中、左对齐、右对齐,后面带宽度
:号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充

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一起使用

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

 

其他

字母b、d、o、x分别是二进制、十进制、八进制、十六进制。

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 
posted @ 2017-08-10 11:40  FlyInDance  阅读(4523)  评论(0编辑  收藏  举报