1. print函数
Python 2中的print是语句,而Python 3中print是函数
Python 2.7
print "Hello, World!" print "No newline", # 末尾逗号抑制换行
Python 3.5
print("Hello, World!") print("No newline", end=" ") # 使用end参数
全面解析两大版本差异及迁移指南
Python 2中的print是语句,而Python 3中print是函数
print "Hello, World!" print "No newline", # 末尾逗号抑制换行
print("Hello, World!") print("No newline", end=" ") # 使用end参数
Python 2中的整数除法行为与Python 3不同
# 整数除法返回整数 print 5 / 2 # 输出 2 # 浮点除法 print 5.0 / 2 # 输出 2.5 print 5 / 2.0 # 输出 2.5
# 整数除法返回浮点数 print(5 / 2) # 输出 2.5 # 使用 // 进行整数除法 print(5 // 2) # 输出 2
Python 3对Unicode的支持更加完善
# 默认字符串是字节串 s = '你好世界' # 字节串 u = u'你好世界' # Unicode字符串 # 需要显式处理编码 print u.encode('utf-8')
# 默认字符串是Unicode s = '你好世界' # Unicode字符串 b = b'byte string' # 字节串 # 自动处理编码 print(s)
Python 3使用as关键字捕获异常
# Python 2.7 try: # 可能出错的代码 except IOError, e: print e # Python 3.5 try: # 可能出错的代码 except IOError as e: print(e)
Python 3中range返回迭代器,xrange被移除
# Python 2.7 range(5) # 返回列表 [0,1,2,3,4] xrange(5) # 返回迭代器 # Python 3.5 range(5) # 返回range对象(迭代器) # xrange() 不再存在
Python 3移除了cmp参数和__cmp__方法
# Python 2.7 sorted(mydict.items(), cmp=lambda x,y: cmp(x[1], y[1])) # Python 3.5 sorted(mydict.items(), key=lambda x: x[1])
Python 3.5引入async/await语法
# Python 3.5特有 import asyncio async def hello(): print("Hello") await asyncio.sleep(1) print("World") # 运行异步函数 asyncio.run(hello())
# 在Python 2.7中使用Python 3特性 from __future__ import print_function from __future__ import division from __future__ import unicode_literals from __future__ import absolute_import
# -*- coding: utf-8 -*-
.items()
代替.iteritems()
raw_input()
在Python 3中是input()
class MyClass(metaclass=MyMeta)
语法除非维护遗留系统,否则强烈建议使用Python 3.5或更高版本。Python 3提供了更好的Unicode支持、更简洁的语法和更强大的异步编程能力。
Python 2.7已于2020年停止官方支持
迁移到Python 3是未来发展的必然选择
本文由KouNiao于2025-08-03发表在吾爱品聚,如有疑问,请联系我们。
本文链接:https://521pj.cn/20257179.html
发表评论