【每天1分钟】PYTHON基础之数据类型-字符串(格式化操作符%)
语法格式:
%[(name)][flags][width].[precision]typecode
说明:除了typecode外,其余均为可选项
- (name):字典参数(key值)
- flags
+: 正数前显示"+"号
-:左对齐
<sp>:一个空格,在正数的左侧填充一个空格,从而与负数对齐
0:数字前用 0 填充,而非默认空格
%%:转义,表示普通字符 % - width:显示宽度
- precision: 小数点后精度
- typecode:类型码
typecode 可采用以下的类型
类型 | 说明 |
---|---|
%s | 字符串 (采用str()的显示) |
%r | 字符串 (采用repr()的显示) |
%c | 单个字符 |
%b | 二进制整数 |
%d | 十进制整数 |
%i | 十进制整数 |
%o | 八进制整数 |
%x | 十六进制整数 |
%e | 指数 (基底写为e) |
%E | 指数 (基底写为E) |
%f | 浮点数 |
%F | 浮点数,与上相同 |
%g | 指数(e)或浮点数 (根据显示长度) |
%G | 指数(E)或浮点数 (根据显示长度) |
%% | 字符"%" |
举例如下:
>>> print("%+10x" % 10)
+a
>>> print("%04d" % 5)
0005
>>> print("%6.3f" % 2.3)
2.300
>>> print("I'm %s. I'm %d year old" % ('John', 40))
I'm John. I'm 40 year old
>>> print("I'm %(name)s. I'm %(age)d year old, and I earn %(money)+7.2f yuan every month." % {'name':'John', 'age':40, 'money': 12345.678})
I'm John. I'm 40 year old, and I earn +12345.68 yuan every month.
>>>