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 
时间: 2024-08-30 06:15:10

Python格式化、显示颜色的相关文章

Python 格式化输出 ( 颜色 )

简介: Python 中如果想让输出有颜色显示,实现起来还是挺容易的,你需要拥有 termcolor 的知识! 参考地址:https://pypi.python.org/pypi/termcolor/1.1.0 开整: shell > pip install termcolor # 如果没有该模块, 要先安装 shell > ipython # 进入 ipython In [1]: import termcolor # 导入该模块 In [2]: termcolor. termcolor.AT

Python格式化字符串~转

Python格式化字符串 在编写程序的过程中,经常需要进行格式化输出,每次用每次查.干脆就在这里整理一下,以便索引. 格式化操作符(%) "%"是Python风格的字符串格式化操作符,非常类似C语言里的printf()函数的字符串格式化(C语言中也是使用%). 下面整理了一下Python中字符串格式化符合: 格式化符号 说明 %c 转换成字符(ASCII 码值,或者长度为一的字符串) %r 优先用repr()函数进行字符串转换 %s 优先用str()函数进行字符串转换 %d / %i

python格式化输出及大量案例

python格式化输出符号及大量案例 1.格式化输出符号 python格式化输出符号 格式化符号 含义 %c 转化成字符 %r 优先使用repr()函数进行字符串转化 %s 转换成字符串,优先使用str() %d或%i 转化成有符号十进制 %u 转化成无符号十进制 %o 转化成无符号八进制数 %x或%X 转化成无符号十六进制数,x或X代表转化后以小写或者大写形式输出 %e或%E 转化成科学计数法,e或E代表以小写或者大写形式输出 %f或%F 转化成浮点数 %g或%G %e和%f 或 %E和%F的

Python格式化字符串知多少

字符串格式化相当于字符串模板.也就是说,如果一个字符串有一部分是固定的,而另一部分是动态变化的,那么就可以将固定的部分做成模板,然后那些动态变化的部分使用字符串格式化操作符(%) 替换.如一句问候语:“Hello 李宁”,其中“Hello”是固定的,但“李宁”可能变成任何一个人的名字,如“乔布斯”,所以在这个字符串中,“Hello”是固定的部分,而“李宁”是动态变化的部分,因此,需要用“%”操作符替换“李宁”,这样就形成了一个模板. Hello %s 上面的代码中,“%”后面的s是什么呢?其实字

Python格式化输出字符串 (%, format(), f&#39;&#39;)

格式说明符/占位符:% 目的:格式与内容分离,制作复杂的公共字符串模板,让某些位置变成动态可输入的. 用法:' %[datatype]  '  % (data, data, ...) %前设置输出格式,用引号括起来:%后设置输出内容,格式部分有几个%,内容部分就有几个数据,多个数据时用小括号括起来,并用逗号分隔. 需要输出%时,可以用%%转义,就取消了占位符的作用 print('3%%%s' % 'gg') 结果: 3%gg 整型 %o 八进制 ,%d  (或%i)十进制,%x 十六进制 pri

python格式化字符及转义字符

 Python格式化字符串的替代符以及含义     符   号     说     明       %c  格式化字符及其ASCII码       %s  格式化字符串       %d  格式化整数       %u  格式化无符号整型       %o  格式化无符号八进制数       %x  格式化无符号十六进制数       %X  格式化无符号十六进制数(大写)       %f  格式化浮点数字,可指定小数点后的精度       %e  用科学计数法格式化浮点数       %E

Python格式化输出

python 格式化输出细节,以备忘 转载自: http://www.cnblogs.com/plwang1990/p/3757549.html 1. 打印字符串 print ("His name is %s" % ("David")) 2.打印整数 print ("He is %d years old" % (25)) 3.打印浮点数 print ("His height is %f m" % (1.83)) 4.打印浮点数

ubuntu之修改ls显示颜色

Linux 系统中 ls 文件夹的痛苦我就不说了,为了不伤眼睛,一般 ssh 终端背景都用的黑色,文件夹又是你妈的深蓝色,每次看文件夹都要探头仔细去看.这下彻底解决这个问题. 因为ubuntu下的/etc/目录里没有DIR_COLORS, 所以费了点劲儿. 1. 利用dircolors命令,查看我们的系统当前的文件名称显示颜色的值,然后利用管道重定向到用户目录下的任意一个文件(这里我们创建了一个.dircolors文件) 命令1: cd ~ 命令2: dircolors -p > .dircol

EasyUI datagrid 格式化显示数据

http://blog.163.com/[email protected]/blog/static/103242241201512502532379/ 设置formatter属性,是一个函数,格式化函数有3个参数: The cell formatter function, take three parameters:value: the field value.rowData: the row record data.rowIndex: the row index. 一.格式化显示性别 后台传过