百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 热门文章 > 正文

python2.x和python3.x的一些区别 python2.x和3.x的版本区别

bigegpt 2024-10-21 03:51 10 浏览

1 使用 __future__的模块

python3.x 引入了一些与python2.x不兼容的关键字和特性。2.x中可以通过__future__模块导入新的内容

2 print函数

2.x中print是个语句,3.x中print是个方法,也是说2.x中print 或者print() 、print () 都是可以的,
```
print "magedu.com"
print("magedu.com")
print ("magedu.com")
```
不过3.x中print一定要方法的形式调用
```
print("magedu.com")
```

3 整数除法

python2.x
```
>>> 1/2
0
```
python3.x
```
>>> 1/2
0.5
>>> 1/0
```

4 编码

- python2.x:ASCII的str类型,有unicode() 转成unicode类型 
```
Python 2.7.16 (default, Apr 17 2020, 18:29:03) 
[GCC 4.2.1 Compatible Apple LLVM 11.0.3 (clang-1103.0.29.20) (-macos10.15-objc- on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.getdefaultencoding()
'ascii'
```
- python3.x:Unicode(utf-8)类型str,bytes,bytearrays
```
Python 3.7.3 (default, Mar  7 2020, 00:16:22) 
[Clang 11.0.0 (clang-1100.0.33.16)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.getdefaultencoding()
'utf-8'
>>> 
```

5 xrange 和range

- python2.x xrange
- python3.x range,使用xrange会有异常

6 异常

- python2.x 支持两种格式
```
Python 2.7.16 (default, Apr 17 2020, 18:29:03) 
[GCC 4.2.1 Compatible Apple LLVM 11.0.3 (clang-1103.0.29.20) (-macos10.15-objc- on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> try:
...     a = raw_input("输入一个数:")
...     if not a.isdigit():
...         raise ValueError("a 必须是数字")
... except ValueError as e:
...     print("引发异常:",e)
... 
输入一个数:a
('\xe5\xbc\x95\xe5\x8f\x91\xe5\xbc\x82\xe5\xb8\xb8\xef\xbc\x9a', ValueError('a \xe5\xbf\x85\xe9\xa1\xbb\xe6\x98\xaf\xe6\x95\xb0\xe5\xad\x97',))
>>> try:
...     a = raw_input("输入一个数:")
...     if not a.isdigit():
...         raise ValueError("a 必须是数字")
... except ValueError,e:
...     print("引发异常:",e)
... 
输入一个数:a
('\xe5\xbc\x95\xe5\x8f\x91\xe5\xbc\x82\xe5\xb8\xb8\xef\xbc\x9a', ValueError('a \xe5\xbf\x85\xe9\xa1\xbb\xe6\x98\xaf\xe6\x95\xb0\xe5\xad\x97',))
```
- python3.x 只支持as e的这种
```
Python 3.7.3 (default, Mar  7 2020, 00:16:22) 
[Clang 11.0.0 (clang-1100.0.33.16)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> try:
...     a = input("输入一个数:")
...     if not a.isdigit():
...         raise ValueError("a 必须是数字")
... except ValueError as e:
...     print("引发异常:",e)
... 
输入一个数:a
引发异常: a 必须是数字
>>> 
```

7 next方法

- python2.x next() 或者.next()
- python3.x next() __next__

8 input方法

- python2.x raw_input()
- python3.x input()

9 iter和list

- python2.x 有些迭代对象直接转成list了:dict.key(),dict.values(), map, reduce,filter等等
```
Python 2.7.16 (default, Apr 17 2020, 18:29:03) 
[GCC 4.2.1 Compatible Apple LLVM 11.0.3 (clang-1103.0.29.20) (-macos10.15-objc- on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> lst = map(lambda x:int(x), [x for x in "123456789"])
>>> type(lst)
<type 'list'>
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> dt = {x:x for x in range(10)}
>>> dt.values()
dict_values([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> dt.keys()
dict_keys([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> dt.items()
dict_items([(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)])
>>> 
```
- python3.x 默认返回的是可迭代对象:dict.key(),dict.values(), map, reduce,filter等等
```
Python 3.7.3 (default, Mar  7 2020, 00:16:22) 
[Clang 11.0.0 (clang-1100.0.33.16)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> lst = map(lambda x:int(x), [x for x in "123456789"])
>>> type(lst)
<class 'map'>
>>> lst
<map object at 0x10457a128>
>>> 
>>> dt = {x:x for x in range(10)}
>>> dt.values()
dict_values([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> dt.keys()
dict_keys([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> dt.items()
dict_items([(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)])
>>> 
```

10 字典

- python2.x  字典插入无序
```
Python 2.7.16 (default, Apr 17 2020, 18:29:03) 
[GCC 4.2.1 Compatible Apple LLVM 11.0.3 (clang-1103.0.29.20) (-macos10.15-objc- on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> dt = {}
>>> dt["a"] = "A"
>>> dt["b"] = "B"
>>> dt["c"] = "C"
>>> dt
{'a': 'A', 'c': 'C', 'b': 'B'}
>>> 
```
- python3.5以后,字典插入有序
```
>>> dt = {}
>>> dt["a"] = "A"
>>> dt["b"] = "B"
>>> dt["c"] = "C"
>>> dt
{'a': 'A', 'b': 'B', 'c': 'C'}
>>> 
```

11 字符串格式化

- python2.x  % 
```
>>> a = "%d+%d=%d" %(1,2,3)
>>> a
'1+2=3'
```
- python3.x  format 和f
```
Python 3.7.3 (default, Mar  7 2020, 00:16:22) 
[Clang 11.0.0 (clang-1100.0.33.16)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = "{}+{}={}".format(1,2,3)
>>> a
'1+2=3'
>>> a = 1
>>> b = 2 
>>> c = 3
>>> d = f"{a}+{b}={c}"
>>> d
'1+2=3'
```

12 True和False

- python2.x True 可以被赋值
```
Python 2.7.16 (default, Apr 17 2020, 18:29:03) 
[GCC 4.2.1 Compatible Apple LLVM 11.0.3 (clang-1103.0.29.20) (-macos10.15-objc- on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> True + True
2
>>> True = 0
>>> True + True
0
>>> 
```
- python3.x True是关键字
```
Python 3.7.3 (default, Mar  7 2020, 00:16:22) 
[Clang 11.0.0 (clang-1100.0.33.16)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> True+True
2
>>> True = 0
  File "<stdin>", line 1
SyntaxError: can't assign to keyword
>>> 
```
python2.x 里面 while 1 要比while True 速度快一些(来自你像从前一样的Python学习笔记-python天坑系列)
```
?  Desktop cat python2.py 
#! /usr/bin/python
# -*- coding: utf-8 -*-
 
import timeit
 
def while_one():
    i = 0
    while 1:
        i += 1
        if i == 10000000:
            break
 
def while_true():
    i = 0
    while True:
        i += 1
        if i == 10000000:
            break
 
if __name__ == "__main__":
    w1 = timeit.timeit(while_one, "from __main__ import while_one", number=3)
    wt = timeit.timeit(while_true, "from __main__ import while_true", number=3)
    print "while one: %s\nwhile_true: %s" % (w1, wt)
?  Desktop python python2.py
while one: 0.646219015121
while_true: 1.01446509361
```

欢迎小伙伴来补充

相关推荐

Docker篇(二):Docker实战,命令解析

大家好,我是杰哥上周我们通过几个问题,让大家对于Docker有了一个全局的认识。然而,说跟练往往是两个概念。从学习的角度来说,理论知识的学习,往往只是第一步,只有经过实战,才能真正掌握一门技术所以,本...

docker学习笔记——安装和基本操作

今天学习了docker的基本知识,记录一下docker的安装步骤和基本命令(以CentOS7.x为例)一、安装docker的步骤:1.yuminstall-yyum-utils2.yum-con...

不可错过的Docker完整笔记(dockerhib)

简介一、Docker简介Docker是一个开源的应用容器引擎,基于Go语言并遵从Apache2.0协议开源。Docker可以让开发者打包他们的应用以及依赖包到一个轻量级、可移植的容器中,...

扔掉运营商的 IPTV 机顶盒,全屋全设备畅看 IPTV!

其实现在看电视节目的需求确实大大降低了,折腾也只是为了单纯的让它实现,享受这个过程带来的快乐而已,哈哈!预期构想家里所有设备直接接入网络随时接收并播放IPTV直播(电信点播的节目不是太多,但好在非常稳...

第五节 Docker 入门实践:从 Hello World 到容器操作

一、Docker容器基础运行(一)单次命令执行通过dockerrun命令可以直接在容器中执行指定命令,这是体验Docker最快捷的方式:#在ubuntu:15.10容器中执行ech...

替代Docker build的Buildah简单介绍

Buildah是用于通过较低级别的coreutils接口构建OCI兼容镜像的工具。与Podman相似,Buildah不依赖于Docker或CRI-O之类的守护程序,并且不需要root特权。Builda...

Docker 命令大全(docker命令大全记录表)

容器生命周期管理run-创建并启动一个新的容器。start/stop/restart-这些命令主要用于启动、停止和重启容器。kill-立即终止一个或多个正在运行的容器rm-于删除一个或...

docker常用指令及安装rabbitMQ(docker安装rabbitmq配置环境)

一、docker常用指令启动docker:systemctlstartdocker停止docker:systemctlstopdocker重启docker:systemctlrestart...

使用Docker快速部署Storm环境(docker部署confluence)

Storm的部署虽然不是特别麻烦,但是在生产环境中,为了提高部署效率,方便管理维护,使用Docker来统一管理部署是一个不错的选择。下面是我开源的一个新的项目,一个配置好了storm与mono环境的D...

Docker Desktop安装使用指南:零基础教程

在之前的文章中,我多次提到使用Docker来安装各类软件,尤其是开源软件应用。鉴于不少读者对此有需求,我决定专门制作一期关于Docker安装与使用的详细教程。我主要以Macbook(Mac平台)为例进...

Linux如何成功地离线安装docker(linux离线安装httpd)

系统环境:Redhat7.2和Centos7.4实测成功近期因项目需要用docker,所以记录一些相关知识,由于生产环境是不能直接连接互联网,尝试在linux中离线安装docker。步骤1.下载...

Docker 类面试题(常见问题)(docker面试题目)

Docker常见问题汇总镜像相关1、如何批量清理临时镜像文件?可以使用sudodockerrmi$(sudodockerimages-q-fdanging=true)命令2、如何查看...

面试官:你知道Dubbo怎么优雅上下线的吗?你:优雅上下线是啥?

最近无论是校招还是社招,都进行的如火如荼,我也承担了很多的面试工作,在一次面试过程中,和候选人聊了一些关于Dubbo的知识。Dubbo是一个比较著名的RPC框架,很多人对于他的一些网络通信、通信协议、...

【Docker 新手入门指南】第五章:Hello Word

适合人群:完全零基础新手|学习目标:30分钟掌握Docker核心操作一、准备工作:先确认是否安装成功打开终端(Windows用户用PowerShell或GitBash),输入:docker--...

松勤软件测试:详解Docker,如何用portainer管理Docker容器

镜像管理搜索镜像dockersearch镜像名称拉取镜像dockerpullname[:tag]列出镜像dockerimages删除镜像dockerrmiimage名称或id删除...