python基础——格式化输出

这篇博客详细介绍了Python中的两种格式化输出方法:%用法和format用法。对于%用法,讲解了整数(八进制、十进制、十六进制)、浮点数(科学计数法、小数形式)和字符串的格式化。在format用法中,不仅介绍了不带编号、带编号以及带关键字的用法,还提到了format的进阶形式,如使用f-string进行格式化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录:
1、%用法
2、format用法

一、%用法

1、整数的格式化

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

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

2、浮点数的格式化

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

>>> print('%f' % 1.11)  # 默认保留6位小数
1.110000
>>> print('%.1f' % 1.11)  # 取1位小数
1.1
>>> print('%e' % 1.11)  # 默认6位小数,用科学计数法
1.110000e+00
>>> print('%.3e' % 1.11)  # 取3位小数,用科学计数法
1.110e+00
>>> print('%g' % 1111.1111)  # 默认6位有效数字
1111.11
>>> print('%.7g' % 1111.1111)  # 取7位有效数字
1111.111
>>> print('%.2g' % 1111.1111)  # 取2位有效数字,自动转换为科学计数法
1.1e+03

3、字符串的格式化

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

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

在这里插入图片描述

二、format用法

(1)不带编号,即“{}”
(2)带数字编号,可调换顺序,即“{1}”、“{2}”
(3)带关键字,即“{a}”、“{tom}”

>>> print('{} {}'.format('hello','world'))  # 不带字段
hello world
>>> print('{0} {1}'.format('hello','world'))  # 带数字编号
hello world
>>> 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

format进阶用法

上面的(1)格式化可以改写成下式
f"xxxx"
可在字符串前加f以达到格式化的目的,在{}里加入对象,此为format的另一种形式:

>>> a = 'man'
>>> b = 'women'
>>> print(f'男人{}女人{}')  
>>> print('男人{}女人{}'.format(a,b))
男人man女人women
男人man女人women
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值