haibaraxx的个人博客分享 http://blog.sciencenet.cn/u/haibaraxx

博文

Python3: 格式化输出 print()

已有 18419 次阅读 2017-5-31 04:40 |个人分类:Python|系统分类:科研笔记| 格式化输出

参考: http://blog.csdn.net/lcore/article/details/9057967


  1. print(...)  

  2.    print(value, ..., sep=' ', end='n', file=sys.stdout, flush=False) # n表示换行



>>> name1 = 'Jane'

>>> name2 = 'Liz'

>>> num1 = 1

>>> num2 = 2


>>> print (name1 + ',' + name2)

Jane,Liz

>>> print (name1 + name2, sep='|' )

Jane|Liz

>>> print (name1, name2, num1, num2, sep=' -- ', end='...n')

Jane -- Liz -- 1 -- 2...


格式化输出


方法一:

print (format_string %(arguments_to_convert))

e.g. print ('There are %d punctuation marks.' %(count))


1. 输出整数。%d

>>> print ('Numbers are %d and %d' %(num1,num2))

Numbers are 1 and 2

2. 输出其他进制数

%x --- hex 十六进制

%d --- dec 十进制

%o --- oct 八进制

3. 输出浮点数。 %f

>>> print ('%10.3f' % 3.1415926)  # 整个输出为10列,保留3位小数位数(最后一位按四舍五入进位),默认右对齐,左边用7(10-3)个空格填充。

      3.142  

4. 输出字符串。 %s

>>> print ('Names are %s and %s' %(name1, name2))

Names are Jane and Liz

>>>  print ('This is %.3s' %(name1))

This is Jan

>>> print ('That is %10.2s' %(name2)) # 整个输出为10列,变量从开始起截取的长度为2,默认右对齐,左边用8(10-2)个空格填充。

That is         Li


方法二(适用于Python3):format函数

print (format_string.format(arguments_to_convert))

e.g. print('There are {0:d} punctuation marks.'.format(count) )

                  - {参数的序号:格式说明符}

参数的序号从0开始编号,可以不按顺序;若不声明(不写),则按照format函数第0,1,2...个参数的默认顺序。

格式说明符又叫格式限定符。




{0: <5d} - 第0个参数,左对齐,以十进制整数的方式输出,输出共占5列(填不满默认右边填充空格)。。

{1: 5.2f} - 第1个参数,默认右对齐,以浮点数的方式输出,保留2位小数位数,输出共占5列(填不满默认左边填充空格)。





https://blog.sciencenet.cn/blog-3031432-1058094.html

上一篇:Python3: 提示输入——input函数
下一篇:Emacs: 系列教程 & GNU Emacs Reference Card
收藏 IP: 134.1.1.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-6-2 07:01

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部