Python2
Python2中的print不是个函数;
>>> print("hello!")
hello!
>>> print"hello!"
hello!
>>> print "The num:%d , the str :%s."%(1,'Tom')
The num:1 , the str :Tom.
输出结果到文件:
>>> a,b = 1,2
>>> output=open("reult.txt","w+")
>>> print>>output,"想输出的结果",a,b
Python 2.6支持新的print()语法:
from __future__ import print_function
print("Hello", "world!", sep=' ')
Hello world!
Python3
Python3中是print()函数, Python 2.6与Python 2.7部分地支持这种形式的print()
>>> print"The num:%d , the str :%s."%(1,'Tom')
SyntaxError: invalid syntax
>>> print("The num:%d , the str :%s."%(1,'Tom'))
The num:1 , the str :Tom.
使用help()查看内置函数print()的使用方法:
>>> help(print)
Help on built-in function print in module builtins:
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.
输出结果到文件
>>> output=open("reult.txt","w+")
>>> print("想输出的内容",file=output)
格式化输出:
format()
括号及其里面的字符 (称作格式化字段) 将会被 format() 中的参数替换:
>>> f,r,u = 1,2,3
>>> print(' the num1:{} \n num2: {} \n the num3: {}'.format(f,r,u))
the num1:1
num2: 2
the num3: 3
在括号中的数字用于指向传入对象在 format() 中的位置:
>>> f,r,u = 1,2,3
>>> print(' the num1:{2} \n num2: {1} \n the num3: {0}'.format(f,r,u))
the num1:3
num2: 2
the num3: 1