本文共 1503 字,大约阅读时间需要 5 分钟。
引言
虽然用python写过不少脚本了,但总感觉串不起来的样子。整好在github上看到一个100天学python的帖子(),闲来无事,每天重温一下吧,顺便记录下来。有错误的,欢迎指正啦。
一、print()函数
python3中,print变成了函数。
print('hello, world!')print("你好,世界!")print('你好', '世界')print('hello', 'world', sep=', ', end='!')print('goodbye, world', end='!\n')
1.print('hello, world!')
print函数里,字符串需要用单引号对,或双引号对,或三引号对括起来。三引号对可以跨行,当然也可以用反斜杠(\)来跨行。
print("hello, world!")>>>hello, world!
2.print("你好, 世界!")
print函数里,中文字符串输出同英文字符串输出。由于python3字符编码格式已经由python2里的unicode编码集改为python3的utf-8编码集,所以不会出现python2里令人头大的编码问题。
print("你好,世界!")print(u"你好,世界!") #python2写法>>>你好,世界!
3.print("你好", “世界”)
print函数里,也支持分开写,同上,主要用途应该是方便下面这个写法,或者输出太长的时候,方便代码整洁吧。
print('你好', "世界")>>>你好 世界
4.print('hello', 'world', sep=', ', end='!')
sep(separate)本意就是分开,就是说输出的两个词语中间用逗号隔开,结尾“!”。
print('hello', 'world', sep=', ', end='!')>>>hello, world!
5.print('goodbye, world', end='!\n')
'\n'为转义字符,同其他语言一样,换行的意思。
print('goodbye, world', end='!\n')>>>goodbye, world!>>>
6.总结
来自builtins.py:以下为print函数的源代码。也可以通过help(print)查看函数参数说明。
def print(self, *args, sep=' ', end='\n', file=None): # known special case of print """ print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to 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. """
转载地址:http://emsti.baihongyu.com/