python2使用python3print_Pythpon3与Python2中print的使用

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值