python2与python3属性差异总结2
参见李天生老师的python基础教程废弃语法差异
一、print 语句被 Python3 废弃,统一使用 print 函数
二、exec 语句被 python3 废弃,统一使用 exec 函数
三、execfile 语句被 Python3 废弃,推荐使用
exec(open("./filename").read())
四、不相等操作符"<>"被 Python3 废弃,统一使用"!=“
五、long 整数类型被 Python3 废弃,统一使用 int
六、 xrange 函数被 Python3 废弃,统一使用 range,Python3 中range 的机制也进行修改并提高了大数据集生成效率
七、Python3 中这些方法再不再返回 list 对象:dictionary 关联的keys()、values()、items(),zip(),map(),filter(),但是可以通过 list 强行转换:
newDict={"a":1,"b":2,"c":3}
print(newDic.keys())
print(list(newDic.keys()))
八. 迭代器 iterator 的 next()函数被 Python3 废弃,
统一使用 next(iterator)
九. raw_input 函数被 Python3 废弃,统一使用
input 函数
十. 字典变量的 has_key 函数被 Python 废弃,统
一使用 in 关键词
如:python2中
newDict={"a":1,"b":2,"c":3}
print newDict.has_key("a")
而Python3中是这样
newDict={"a":1,"b":2,"c":3}
#方式一:
for key in newDict:
print(key+':'+str(newDict[key]))
#方式二:
for key in newDict.keys():
print(key+':'+str(newDict[key]))
#方式三:
for key,value in newDict.items():
print(key+':'+str(value))
#方式四:
for (key,value) in newDict.items():
print(key+":"+str(value))
十一、 file 函数被 Python3 废弃,统一使用 open 来处理文件,可以通过 io.IOBase 检查文件类型
十二. apply 函数被 Python3 废弃
十三. 异常 StandardError 被 Python3 废弃,统一
使用 Exception
十四、去除``,全部改用repr()
repr() 函数将对象转化为供解释器读取的形式。
list1=[1,2,3]
print(type(repr(list1)))
以上内容在python基础教程中有详细讲解