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’)

常见格式:
在这里插入图片描述
常见转义字符:
在这里插入图片描述

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chde2Wang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值