格式化的相关内容
%d ----格式化整 只可以是数字,当然如果是小数就把小数部分去掉
msg = "my name is %s,and my age is %d" % ("djh", 18) print(msg) 结果 my name is djh,and my age is 18 msg = "my name is %(name)s,and my age is %(age)d" % {"name":"djh", "age":18}//另一种写法而已没什么 print(msg) 结果 my name is djh,and my age is 18
%f ----格式化浮点数,可以指定小数点后的精度
print('%f' % 27.56463462) 结果 27.564635//默认保存6位,四舍五入 print('%.2f' % 27.56463462) 结果 27.56//保存两位 msg = "%.2f%%" % 27.4677 //想要打印 % 这个符号,必须要两个% 即%% print(msg) 结果 27.47%
%s ----格式化字符串 其实%s是万能的格式化字符 ,接受啥类型的都可以,还可以自己限定截取多少位
msg = "my name is %s,and my age is %s" % ("djh", "18") //("djh",18)也行 print(msg) 结果 my name is djh,and my age is 18 msg = "my name is %s,and my age is %s" % ("djh", [18,19]) print(msg) 结果 my name is djh,and my age is [18, 19] msg = "asd %.4s" % "Fgsdgsdgsdg"//截取4位 print(msg) 结果 asd Fgsd
%o ----格式化无符号八进制数
>>>'%d的八进制数是%o' % (123,123)
>>>’123的八进制数是173
%x ----格式化无符号十六进制//注意,只可以对整数进行变换,如果是小数就会报错
>>>'%x' % 27
>>>1b
%X ----和%x一样,格式化无符号16进制数,但是字母是变成大写
>>>'%X' & 27
>>>1B
%e ----用科学记数法格式化浮点数
>>>'%e' %27.1234567
>>>2.712346e+01 //小数点后最多6位
%E ----同%e 只是科学记数法时将e变成E就ok
还有一些辅助指令
1:对浮点数而言 ‘%m.nf’ 其中m是指定宽度,n是保留多少位小数(注:这里的m不只是只对浮点型有用,对整数或者16进制也有用)
>>>'%8.2f' %27.125
>>> 27.12//默认右对齐,一共8个位置,不够的位置用空格填充
如果不想用空格填充,只能选择用0填充,是直接将0填充在原本的数字前面,如果是左对齐,后面虽然还有空位,但只用空格填充,因为0是直接在原本数字前面填充的!!!
(用空格填充也是对其他进制的有用,不知浮点型!)
2:'%0m.nf' 只要再m.nf前面加0就ok
>>>'%08.2f' % 27.125
>>>00027.12
3:左对齐在最前面加给‘-‘号就ok
>>>'%-8.2f' % 27.125
>>>27.13
4:在正数前面加个+
>>>'%+5d' % 27.123
>>> +27
5:在16进制前加0x或0X(主要看你自己写的时候用的是%x或者%X)8进制前加0o(只可以是0o)
>>>'%#X' % 27
>>>0X1B
//format()函数的格式化
后面的参数被组成元组 msg = "my name is {},and my age is {}" .format("djh",18)//这种写法是将后面的两个参数组成一个元组,前面字符串的{}内没写任何东西相当于默认从0开始往后数,然后 根据这个数字在后面的那个元组里索引,但如果后面的元组的个数少于前面字符串的{}数,自然就出错,因为这样的话索引的下标会越界,自然就错了 print(msg) 结果 my name is djh,and my age is 18 msg = "my name is {1},and my age is {0}" .format("djh",18) print(msg) 结果 my name is 18,and my age is djh 后面的参数被组陈字典 msg = "my name is {name},and my age is {age}" .format(name="djh",age=18) print(msg) 结果 my name is djh,and my age is 18