python 格式化输出%和format

1 %用法

1.1整数的输出

%o —— oct 八进制
%d —— dec 十进制
%x —— hex 十六进制

print('%o' % 20)  #24
print('%d' % 20)  #20
print('%x' % 20)  #14

1.2浮点数输出

%f ——默认保留小数点后面六位有效数字
  %.3f,保留3位小数位
%e ——默认保留小数点后面六位有效数字,指数形式输出
  %.3e,保留3位小数位,使用科学计数法
%g ——在保证六位有效数字的前提下,使用小数方式,否则使用科学计数法
  %.3g,保留3位有效数字,使用小数或科学计数法

1.3round四舍五入

round(number[, ndigits])
参数:
number - 这是一个数字表达式。
ndigits - 表示从小数点到最后四舍五入的位数。默认值为0。
返回值
该方法返回x的小数点舍入为n位数后的值。

print(round(1.1125))     #1
print(round(1.1135,3))  #1.113
print(round(1.1125,3))  #1.113

1.4字符串输出

%s
%10s——右对齐,占位符10位
%-10s——左对齐,占位符10位
%.2s——截取2位字符串
%10.2s——10位占位符,截取两位字符串

print('%s' % 'hello world')
print('%s' % 1)
print('%20s' % 'hello world')
print('%-20s' % 'hello world')
print('%.2s' % 'hello world')
print('%10.2s' % 'hello world')
print('%-10.2s' % 'hello world')

输出结果:

print(’%s’ % ‘hello world’)
print(’%s’ % 1)
print(’%20s’ % ‘hello world’)
print(’%-20s’ % ‘hello world’)
print(’%.2s’ % ‘hello world’)
print(’%10.2s’ % ‘hello world’)
print(’%-10.2s’ % ‘hello world’)

常见格式:
python 格式化输出%和format_第1张图片
常见转义字符:
python 格式化输出%和format_第2张图片

2 format用法

format()功能更强大,该函数把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号‘{}’作为特殊字符代替‘%’

2.1位置匹配

(1)不带编号,即“{}”

(2)带数字编号,可调换顺序,即“{1}”、“{2}”

(3)带关键字,即“{a}”、“{tom}”

print('{} {}'.format('hello','world'))
print('{0} {1}'.format('hello', 'world'))
print('{0} {1} {0}'.format('hello','world'))
print('{1} {1} {0}'.format('hello','world'))
print('{a} {tom} {a}'.format(tom='hello',a='world'))

输出结果

hello world
hello world
hello world hello
world world hello
world hello world

print( '{0}, {1}, {2}'.format('a', 'b', 'c'))
print('{}, {}, {}'.format('a', 'b', 'c'))
print( '{2}, {1}, {0}'.format('a', 'b', 'c'))
print('{2}, {1}, {0}'.format(*'abc'))  # 可打乱顺序
print('{0}{1}{0}'.format('abra', 'cad'))  # 可重复

输出结果:

a, b, c
a, b, c
c, b, a
c, b, a
abracadabra

import datetime
d=datetime.datetime(2010,7,4,12,15,34)
print('{:%Y-%m-%d %H:%M:%S}'.format(d))

输出结果:

2010-07-04 12:15:34

2.2左中右对齐及位数补全

(1)< (默认)左对齐、> 右对齐、^ 中间对齐、= (只用于数字)在小数点后进行补齐

(2)取位数“{:4s}”、"{:.2f}"等

points=19
total=22
print('Correct answers: {:.2%}'.format(points/total))
print('{} is {:.2f}'.format(1.123,1.123))
print('{0} is {0:>10.2f}'.format(1.123))
print('{:+f}; {:+f}'.format(3.14, -3.14))  # 总是显示符号
print('{:,}'.format(1234567890))

输出结果:

Correct answers: 86.36%
1.123 is 1.12
1.123 is 1.12
+3.140000; -3.140000
1,234,567,890

你可能感兴趣的:(python 格式化输出%和format)