Python3.3 print函数用法,print 格式化输出



转载至:

http://blog.sina.com.cn/s/blog_540775a30101bkek.html


1. 输出字符串

>>> strHello = 'Hello World'
>>> print(strHello)
Hello World

2. 格式化输出整数

支持参数格式化,与C语言的printf类似

>>> strHello = "the length of (%s) is %d" %('Hello World',len('Hello World'))
>>> print(strHello)
the length of (Hello World) is 11

3. 格式化输出16进制,十进制,八进制整数

%x --- hex 十六进制
%d --- dec 十进制
%o --- oct 八进制
>>> nHex = 0xFF
>>> print("nHex = %x,nDec = %d,nOct = %o" %(nHex,nHex,nHex))
nHex = ff,nDec = 255,nOct = 377

4.格式化输出浮点数(float)

>>>import math
>>> print('PI=%f'%math.pi)
PI=3.141593
>>> print ("PI = .3f" % math.pi)
PI = 3.142
>>> print ("PI = %-10.3f" % math.pi
PI = 3.142 
>>> print ("PI = d" % int(math.pi))
PI = 000003

5. 格式化输出浮点数(float) 

>>> precise = 3
>>> print ("%.3s " % ("python"))
pyt
>>> precise = 4
>>> print ("%.*s" % (4,"python"))
pyth
>>> print (".3s " % ("python"))
pyt

6.输出列表(List)

输出列表

>>> lst = [1,2,3,4,'python']
>>> print (lst)
[1, 2, 3, 4, 'python']
输出字典
>>> d = {1:'A',2:'B',3:'C',4:'D'}
>>> print(d)
{1: 'A', 2: 'B', 3: 'C', 4: 'D'}

7. 自动换行

print 会自动在行末加上回车,如果不需要回车,可以采用以下办法:

a) Python 2.x下的print语句在输出字符串之后会默认换行,如果不希望换行,只要在语句最后加一个“,”即可;

b) Python3.x下,print()变成内置函数,加“,”的老方法就行不通了,原因如下:

    查询Python 3.x的Library Reference>Built-in Functions,找到如下条目

        “print([object,...],*, sep=' ', end='\n', file=sys.stdout)

Printobject(s) to the streamfile, separated by sep and followed byend. sep,end and file, if present, must be given as keyword arguments.

All non-keyword arguments are converted to strings likestr() does and written to the stream, separated by sep and followed by end. Bothsep andend must be strings; they can also be None, which means to use the default values. If noobject is given,print() will just write end.

The file argument must be an object with awrite(string) method; if it is not present orNone,sys.stdout will be used. ”

        其中,sep=''和end='\n'均是print()的关键参数,sep的默认值为空,end默认值为换行符,这就是print()在输出后默认换行的原因。相应的,解决办法就是对end赋值:print(something, something,.., end=''),使end值为空,这个换行就消除了。

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值