您的位置:首页 > 编程语言 > Python开发

Python基础知识6:格式化字符、颜色

2017-12-17 00:00 549 查看
字符格式化,有两种方式:
1、通过%占位符方式,%s,%d,%
2、通过format,其中format比较好用,可以居中、可以用%、可以用二进制、可以填充字符自定义;

1、利用%的案例
tp1="i am %s"%"aaa"#
tp2="i am %s age %d"%("alex",18)#顺序关联
tp3="i am %(name)s age %(age)d"%{"name":"alex","age":18}#指定名称,起名字
tp4="percent%.2f"%99.567#保留小数点几位
tp5="i am %(pp).2f"%{"pp":12.45667,}#指定名称,保留两位小数
tp6="i am %(pp).2f%%"%{"pp":13.34566,}#用双%%来引用%
print("tp1:",tp1)
print("tp2:",tp2)
print("tp3:",tp3)
print("tp4:",tp4)
print("tp5:",tp5)
print("tp6:",tp6)
执行结果:



2、利用formattp1="i am {},age{},you are{}".format("hhh",123,"yyy")#顺序填充
tp2="i am {},age{},you are{}".format(*["hhh",123,"yyy"])#动态参数填充
tp3="i am {0},age{1},you are{0} too".format("hhh",123)#占位符索引填充,顺序填充
tp4="i am {0},age{1},you are{0} too".format(*["hhh",123])#占位符索引填充,动态参数填充
tp5="i am {name},age{age},you are{name} too".format(name="hhh",age=123)#指定名称填充,名称顺序可变
tp6="i am {name},age{age},you are{name} too".format(**{"name":"hhh","age":123})#指定名称,动态参数,字典需要**
tp7="i am {0[0]},age{0[1]},you are{0[2]}".format([1,2,3],[11,22,33])#通过列表传递
tp8="i am {:s},age{:d},money{:f}".format("hh",18,88.11)#格式化字符,S字符,d整数,f浮点型
tp9="i am {name:s},age{age:d}".format(name="hh",age=18)#指定名称,S字符,d整数,f浮点型
tp10="i am {name:s},age{age:d}".format(**{"name":"hhh","age":123})#动态参数+指定名称,S字符,d整数,f浮点型
tp11="numbers:{:b},{:o},{:d},{:x},{:X},{:%}".format(15,15,15,15,15,3.666)#格式化字符,b二进制,d整型
tp12="numbers:{0:b},{0:o},{0:d},{0:x},{0:X},{0:%}".format(15)#格式化+索引,b是字节型,o是八进制,x是16进制
tp13="numbers:{num:b},{num:o},{num:d},{num:x},{num:X},{num:%}".format(num=15)#格式化+指定名称执行结果:

tp1: i am hhh,age123,you areyyy
tp2: i am hhh,age123,you areyyy
tp3: i am hhh,age123,you arehhh too
tp4: i am hhh,age123,you arehhh too
tp5: i am hhh,age123,you arehhh too
tp6: i am hhh,age123,you arehhh too
tp7: i am 1,age2,you are3
tp8: i am hh,age18,money88.110000
tp9: i am hh,age18
tp10: i am hhh,age123
tp11: numbers:1111,17,15,f,F,366.600000%
tp12: numbers:1111,17,15,f,F,1500.000000%
tp13: numbers:1111,17,15,f,F,1500.000000%

颜色格式:格式: echo "\033[字背景颜色;字体颜色m输入的内容\033[0m" 案例:echo "\033[41;36m write something here \033[0m" ,其中41的位置代表底色, 36的位置是代表字的颜色 那些ascii code 是对颜色调用的始末. \033[ ; m …… \033[0m 案例:a1=input("\033[41;36m write something here \033[0m")#前景色和背景色均设置


a1=input("\033[41;1m write something here \033[0m")#只设置背景色,且加粗



a1=input("\033[36;1m write something here \033[0m")#可以单独识别只设置字体颜色,且加粗

a1=input("\033[36;m write something here \033[0m")#可以单独识别只设置字体颜色,不加粗



字背景颜色范围:40----49 
40:黑 
41:深红 
42:绿 
43:黄色 
44:蓝色 
45:紫色 
46:深绿 
47:白色 

字颜色:30-----------39 
30:黑 
31:红 
32:绿 
33:黄 
34:蓝色 
35:紫色 
36:深绿 
37:白色 
ANSI控制码的说明 \33[0m 关闭所有属性 
\33[1m 设置高亮度 
\33[4m 下划线 
\33[5m 闪烁 
\33[7m 反显 
\33[8m 消隐 
\33[30m -- \33[37m 设置前景色 
\33[40m -- \33[47m 设置背景色 
\33[nA 光标上移n行 
\33[nB 光标下移n行 
\33[nC 光标右移n行 
\33[nD 光标左移n行 
\33[y;xH设置光标位置 
\33[2J 清屏 
\33[K 清除从光标到行尾的内容 
\33[s 保存光标位置 
\33[u 恢复光标位置 
\33[?25l 隐藏光标 
\33[?25h 显示光标  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: