温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在python中格式化输出

发布时间:2020-07-15 10:29:58 来源:亿速云 阅读:157 作者:Leah 栏目:编程语言

怎么在python中格式化输出?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

使用%格式化输出:

整数输出:

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

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

浮点数输出:

%f ——保留小数点后面六位有效数字,%.3f,保留3位小数位
%e ——保留小数点后面六位有效数字,指数形式输出,%.3e,保留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

字符串输出:

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

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

相对基本格式化输出采用‘%’的方法,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

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI