美文网首页
python中的print

python中的print

作者: MoraGG | 来源:发表于2017-07-10 21:43 被阅读0次

2.x中的print不是个函数,输出格式如下

>>>print"There is only %d %s in the sky."%(1,'sun')

Thereisonly 1 suninthe sky.

3.x中的print成了函数,输出格式如下

>>>print("There is only %d %s in the sky."%(1,'sun'))

Thereisonly 1 suninthe sky.

为什么要做出这样的变化,主要原因有以下几点:

1.print不是函数,不能使用help(),对使用者不方便。

python2中help(print)会报错。

python3中,可以使用help(print),清楚的看到print的参数。

print(value, ..., sep='', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream,orto sys.stdout by default.

Optional keyword arguments:

file:  a file-like object (stream); defaults to the current sys.stdout.

sep:  string inserted between values, default a space.

end:  string appended after the last value, default a newline.

flush: whether to forcibly flush the stream.


2.从上面的help(print)中我们也可以看到在print()中的两个重要参数,sep和end。这两个参数使print()相比print多了两个新功能,自定义间隔符(默认空格)和结束符(默认回车)。

>>>print("123","456","789")

123 456 7893

>>>print("123","456","789",sep='-')

123-456-789

>>> t=256

>>>print(t)

256

>>>print(t,end="end")

256 end

>>>print(t,end="end\n")

256 end


3.print()重定向输出文件更加方便。

2.x需要print>>重定向输出,感觉代码很混乱。

>>> out=open("test.txt","w")

>>>print>>out,"123"

3.x中输出文件成了一个参数,使用更方便。

>>> out=open("test.txt","w")

>>>print("123",file=out)


4.python2.x中print语句的格式化输出源自于C语言的格式化输出,这种语法对于C这种静态语言比较适用,但是对于拥有很多先进数据结构的python来说就有点力不从心了。python的元组,列表,字典,集合等不适合用这种结构表示,这些数据结构大多元素用下标表示,在这种结构中写出来很混乱。python3.x的print()函数提供了有点类似C#(不知道这么说对不对)中的格式化输出函数format()。另外print()也兼容原来的格式化输出方式。

>>>print("%s is %s."%('Aoko','good'))

Aoko is good.

format()让输出格式更清晰。

>>>print("{0} is {1}.".format('Aoko','good'))

Aoko is good.

format()支持数组下标,使python中的一些数据结构输出更加方便。

>>> name=["Kaito",5]

>>>print("{0[0]} has {0[1]} dollars.".format(name))

Kaito has 5 dollars.

format()下的格式限定符,和原来的差不多。

>>> x=5.6

>>>print("{0:4f}".format(x))

5.600000

相关文章

网友评论

      本文标题:python中的print

      本文链接:https://www.haomeiwen.com/subject/ahiuhxtx.html