• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python怎么格式化输出

python 搞代码 4年前 (2022-01-09) 18次浏览 已收录 0个评论

使用%格式化输出:

整数输出:

%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 <mark style="color:transparent">本文来源gaodaimacom搞#^代%!码&网*</mark>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

更多Python相关技术文章,请访问Python教程栏目进行学习!

以上就是python怎么格式化输出的详细内容,更多请关注搞代码gaodaima其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python怎么格式化输出

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址