前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python格式化输出(%用法和format用法)

Python格式化输出(%用法和format用法)

作者头像
zeruns
发布2020-03-23 16:26:50
5.2K0
发布2020-03-23 16:26:50
举报
文章被收录于专栏:Zeruns的博客Zeruns的博客

整数的输出

  • %o——Oct八进制
  • %d——Dec十进制
  • %x——Hex十六进制

浮点数(小数)的输出

格式化输出

代码语言:javascript
复制
>>> awsl=2.333
>>> print('%f'%awsl)    #默认保留6位小数
2.333000
>>> print('%.1f'%awsl)  #取1位小数
2.3
>>> print('%e'%awsl)    #默认6位小数,用科学计数法
2.333000e+00
>>> print('%.2e'%awsl)  #取2位小数,用科学计数法
2.33e+00
>>> print('%g'%2.3333333)#默认6位有效数字
2.33333
>>> print('%.5g'%233.33333)#取5位有效数字
233.33
>>> print('%.2g'%2333.3333)#取2位有效数字,自动转换为科学计数法
2.3e+03

内置round()

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

  • round()函数只有一个参数,不指定位数的时候,返回一个整数,而且是最靠近的整数,类似于四舍五入
  • 当指定取舍的小数点位数的时候,一般情况也是使用四舍五入的规则
  • 但是碰到.5的情况时,如果要取舍的位数前的小数是奇数,则直接舍弃,如果是偶数则向上取舍。

注:“.5”这个是一个“坑”,且python2和python3出来的接口有时候是不一样的,尽量避免使用round()函数吧

代码语言:javascript
复制
>>> round(1.1125)  # 四舍五入,不指定位数,取整
1
>>> round(1.1135,3)  # 取3位小数,由于3为奇数,则向下“舍”
1.113
>>> round(1.1125,3)  # 取3位小数,由于2为偶数,则向上“入”
1.113
>>> round(2.675,2)  # 取2位有效小数
2.67

注:round(2.675,2)的结果,结果应该是2.68的,但它偏偏是2.67,为什么?这跟浮点数 的精度有关。在机器中浮点数不一定能精确表达,换算成一串 1和0后可能是无限位数的,机器已经做出了截断处理。因此在机器中保存的2.675这个数字就比实际数字要小那么一点点。这一点点就导致了它离2.67要更近一点点,所以保留两位小数时就近似到了2.67。

字符串输出

  • %s
  • %10s——右对齐,占位符10位
  • %-10s——左对齐,占位符10位
  • %.2s——截取2位字符串
  • %10.2s——10位占位符,截取两位字符串
代码语言:javascript
复制
>>> print('%s' % 'hello world')  # 字符串输出
hello world
>>> print('%20s' % 'hello world')  # 右对齐,取20位,不够则补位
         hello world
>>> print('%-20s' % 'hello world')  # 左对齐,取20位,不够则补位
hello world         
>>> print('%.2s' % 'hello world')  # 取2位
he
>>> print('%10.2s' % 'hello world')  # 右对齐,取2位
        he
>>> print('%-10.2s' % 'hello world')  # 左对齐,取2位
he

格式化输出多个变量

代码语言:javascript
复制
>>> hhh=2333
>>> awsl=2.333
>>> print('%d+%f=%f'%(hhh,awsl,hhh+awsl))
2333+2.333000=2335.333000

格式化符号大全

符 号

描述

%c

格式化字符及其ASCII码

%s

格式化字符串

%d

格式化整数

%u

格式化无符号整型

%o

格式化无符号八进制数

%x

格式化无符号十六进制数

%X

格式化无符号十六进制数(大写)

%f

格式化浮点数字,可指定小数点后的精度

%e

用科学计数法格式化浮点数

%E

作用同%e,用科学计数法格式化浮点数

%g

浮点型数据 会去掉多余的零 至多保留6位

%G

浮点型数据 会去掉多余的零 至多保留6位

%p

用十六进制数格式化变量的地址

格式化操作符辅助指令:

符号

描述

*

定义宽度或者小数点精度

-

用做左对齐

+

在正数前面显示加号( + )

< sp >

在正数前面显示空格

#

在八进制数前面显示零('0'),在十六进制前面显示'0x'或者'0X'(取决于用的是'x'还是'X')

0

显示的数字前面填充'0'而不是默认的空格

%

'%%'输出一个单一的'%'

(var)

映射变量(字典参数)

m.n.

m 是显示的最小总宽度,n 是小数点后的位数(如果可用的话)

format用法

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

位置匹配

  1. 不带编号,即“{}”
  2. 带数字编号,可调换顺序,即“{1}”、“{2}”
  3. 带关键字,即“{a}”、“{tom}”
代码语言:javascript
复制
>>> print('{} {}'.format('zeruns','blog.zeruns.tech'))  # 不带字段
zeruns blog.zeruns.tech
>>> print('{0} {1}'.format('hello','world'))  # 带数字编号
hello world
>>> print('{1}{0}'.format('blog.zeruns.tech','https://'))
https://blog.zeruns.tech
>>> print('{0} {1} {0}'.format('hello','world'))  # 打乱顺序
hello world hello
>>> print('{1} {1} {0}'.format('hello','world'))
world world hello
>>> print('{a} {tom} {a}'.format(tom='hello',a='world'))  # 带关键字
world hello world

#通过位置匹配
>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c')  # 3.1+版本支持
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc')  # 可打乱顺序
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad')  # 可重复
'abracadabra'

#通过名字匹配
>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'

#通过下标或key匹配参数
>>> coord = (3, 5)
>>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
'X: 3;  Y: 5'
>>> a = {'a': 'test_a', 'b': 'test_b'}
>>> 'X: {0[a]};  Y: {0[b]}'.format(a)
'X: test_a;  Y: test_b'

格式转换

  • 'b' - 二进制。将数字以2为基数进行输出。
  • 'c' - 字符。在打印之前将整数转换成对应的Unicode字符串。
  • 'd' - 十进制整数。将数字以10为基数进行输出。
  • 'o' - 八进制。将数字以8为基数进行输出。
  • 'x' - 十六进制。将数字以16为基数进行输出,9以上的位数用小写字母。
  • 'e' - 幂符号。用科学计数法打印数字。用'e'表示幂。
  • 'g' - 一般格式。将数值以fixed-point格式输出。当数值特别大的时候,用幂形式打印。
  • 'f' - 浮点数。将数字以浮点数形式输出,默认6位小数。
  • 'n' - 数字。当值为整数时和'd'相同,值为浮点数时和'g'相同。不同的是它会根据区域设置插入数字分隔符。
  • '%' - 百分数。将数值乘以100然后以fixed-point('f')格式打印,值后面会有一个百分号。
代码语言:javascript
复制
>>> print('{0:b}'.format(3))
11
>>> print('{:c}'.format(20))

>>> print('{:d}'.format(20))
20
>>> print('{:o}'.format(20))
24
>>> print('{:x}'.format(20))
14
>>> print('{:e}'.format(20))
2.000000e+01
>>> print('{:g}'.format(20.1))
20.1
>>> print('{:f}'.format(20))
20.000000
>>> print('{:n}'.format(20))
20
>>> print('{:%}'.format(20))
2000.000000%

format的用法变形

代码语言:javascript
复制
# a.format(b)
>>> "{0} {1}".format("hello","world")
'hello world'

# f"xxxx"
# 可在字符串前加f以达到格式化的目的,在{}里加入对象,此为format的另一种形式:

>>> a = "hello"
>>> b = "world"
>>> f"{a} {b}"
'hello world'

name = 'jack'
age = 18
sex = 'man'
job = "IT"
salary = 9999.99

print(f'my name is {name.capitalize()}.')
print(f'I am {age:*^10} years old.')
print(f'I am a {sex}')
print(f'My salary is {salary:10.3f}')

# 结果
my name is Jack.
I am ****18**** years old.
I am a man
My salary is   9999.990

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-02-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Zeruns 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 整数的输出
  • 浮点数(小数)的输出
    • 格式化输出
      • 内置round()
      • 字符串输出
      • 格式化输出多个变量
      • 格式化符号大全
      • format用法
        • 位置匹配
          • 格式转换
          • format的用法变形
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档