python两种格式化之(“%”和“format”)的用法
一、%的用法
1、格式化输出整数
%o —— oct 八进制
%d —— dec 十进制
%x —— hex 十六进制
1 >>> print('%o' % 20) 2 24 3 >>> print('%d' % 20) 4 20 5 >>> print('%x' % 20) 6 14
2、字符串输出
%s
%10s——右对齐,占位符10位
%-10s——左对齐,占位符10位
%.2s——截取2位字符串
%10.2s——10位占位符,截取两位字符串
1 >>> print('%s' % 'hello world') # 字符串输出 2 hello world 3 >>> print('%20s' % 'hello world') # 右对齐,取20位,不够则补位 4 hello world 5 >>> print('%-20s' % 'hello world') # 左对齐,取20位,不够则补位 6 hello world 7 >>> print('%.2s' % 'hello world') # 取2位 8 he 9 >>> print('%10.2s' % 'hello world') # 右对齐,取2位 10 he 11 >>> print('%-10.2s' % 'hello world') # 左对齐,取2位 12 he
3、字符串格式代码如下
2、format的用法
相对基本格式化输出采用‘%’的方法,format()功能更强大,该函数把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号‘{}’作为特殊字符代替‘%’。
使用方法有两种:b.format(a)和format(a,b)。
基本用法:
(1)不带编号,即“{}”
(2)带数字编号,可调换顺序,即“{1}”、“{2}”
(3)带关键字,即“{a}”、“{tom}”
示例:
1 >>> print('{} {}'.format('hello','world')) # 不带字段 2 hello world 3 >>> print('{0} {1}'.format('hello','world')) # 带数字编号 4 hello world 5 >>> print('{0} {1} {0}'.format('hello','world')) # 打乱顺序 6 hello world hello 7 >>> print('{1} {1} {0}'.format('hello','world')) 8 world world hello 9 >>> print('{a} {tom} {a}'.format(tom='hello',a='world')) # 带关键字 10 world hello world