python中字符串的输出打印:
之前因为偷懒,一直采用%s的方式写程序。看到format总是避而远之,这样很不好。今天就简单汇总一下
1. %s 方式
优点,比较容易理解和记忆。缺点,格式化个数需要对应
1.1 格式化符号
%c 格式化字符及其ASCII码 ,把数字转化为对应的ASCII码,如数字126对应‘~’。(ASCII对应数字0-128,97对应a,122对应z)
%s 格式化字符串 ,如上述代码
%d 格式化整数 ,如上述代码
%u 格式化无符号整型 ,数字舍掉小数
%o 格式化无符号八进制数 ,如数字10对应八进制的12
%x 格式化无符号十六进制数 ,如数字10对应十六进制的a
%X 格式化无符号十六进制数(大写) 如数字10对应十六进制的A
>> print("This is a test, today is Oct. %s"%27)
>> print("This is a test, today is Oct. %d"%27)
>> print("This is a test, today is Oct. %u"%27.6)
>> print("This is a test, today is %s %d"%("Oct.",27))
上面三个脚本的输入均为:
This is a test, today is Oct. 27
%f 格式化浮点数字,可指定小数点后的精度
%e 用科学计数法格式化浮点数
%E 作用同%e,用科学计数法格式化浮点数
>> print("%f"%10)
>> print("%.3f"%10)
>> print("%3.f"%10)
>> print("%3.3f"%10)
>> print("%7.3f"%10)
>> print("%e"%10)
>> print("%E"%10)
上面的输出分别为:
10.000000 默认精度小数点后6位
10.000 .3 表示小数点后3位
10 3. 表示一共输出3个位宽
10.000 3.3以小数点位数位主,位宽定义数要小于实际输出数,按实际走
10.000 7.3位宽一共为7,小数点后3位
1.000000e+1
1.000000E+1
1.2 格式化操作符辅助指令
* : 定义宽度或者小数点精度
- :用做左对齐
+: 在正数前面显示加号( + )
<sp>: 在正数前面显示空格
#:在八进制数前面显示零(‘0’),在十六进制前面显示’0x’或者’0X’(取决于用的是’x’还是’X’)
0 : 显示的数字前面填充’0’而不是默认的空格
%: ‘%%‘输出一个单一的’%’
(var): 映射变量(字典参数)
m.n. : m 是显示的最小总宽度,n 是小数点后的位数(如果可用的话)
2. format格式
格式更加多变和灵活了
2.1 使用简单举例
>> print("This is a test, today is Oct. {}".format(27))
>> print("This is a test, today is {} {}".format("Oct.",27))
>> print("This is a test, today is {0} {1}".format("Oct.",27))
>> print("This is a test, today is {1} {0}".format(27,"Oct."))
>> print("This {2} a test, today {2} {0} {1}".format("Oct.",27,"is"))
>> print("This is a test, today is {month} {day}".format(month="Oct.",day=27))
>> print("This is a test, today is {0[0]} {0[1]}".format(["Oct.",27]) # 0必须有
>> print("This is a test, today is {month} {day}".format(**{"month":"Oct","day":27})) # **必须有
上述代码输出均为:
This is a test, today is Oct. 27
2.2 格式化数字的方法(摘自https://www.runoob.com/python/att-string-format.html)
3.1415926 ----- {:.2f} 3.14 保留小数点后两位
3.1415926 -----{:+.2f} +3.14 带符号保留小数点后两位
-1 ----- {:+.2f} -1.00 带符号保留小数点后两位
2.71828 ----- {:.0f} 3 不带小数
5 ----- {:0>2d} 05 数字补零 (填充左边, 宽度为2)
5 ----- {:x<4d} 5xxx 数字补x (填充右边, 宽度为4)
10 ----- {:x<4d} 10xx 数字补x (填充右边, 宽度为4)
1000000 ----- {:,} 1,000,000 以逗号分隔的数字格式
0.25 ----- {:.2%} 25.00% 百分比格式
1000000000 ----- {:.2e} 1.00e+09 指数记法
13 ----- {:>10d} 13 右对齐 (默认, 宽度为10)
13 ----- {:<10d} 13 左对齐 (宽度为10)
13 ----- {:^10d} 13 中间对齐 (宽度为10)
11 ----- 进制
1011 ---- ‘{:b}’.format(11)
11 ---- ‘{:d}’.format(11)
13 ---- ‘{: o}’.format(11)
b ---- ‘{:x}’.format(11)
0xb ---- ‘{:#x}’.format(11)
0XB ---- ‘{:#X}’.format(11)
^, <, > 分别是居中、左对齐、右对齐,后面带宽度, : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。
- 表示在正数前显示 +,负数前显示 -; (空格)表示在正数前加空格
b、d、o、x 分别是二进制、十进制、八进制、十六进制。
此外我们可以使用大括号 {} 来转义大括号,如下实例:
print("This is {}, not {{0}}".format(0))
This is 0,not {0}