xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Python 2 to Python 3 convert

Python 2 to Python 3 convert

2to3, 自动将 Python 2 代码转为 Python 3 代码

https://docs.python.org/zh-cn/2/library/2to3.html

$ 2to3 example.py

# -w
$ 2to3 -w example.py

$

demo

before, Python 2

def greet(name):
    print "Hello, {0}!".format(name)
print "What's your name?"
name = raw_input()
greet(name)

after, Python 3 ✅

def greet(name):
    print("Hello, {0}!".format(name))
print("What's your name?")
name = input()
greet(name)

2to3 in action

# coding: utf8

__author__ = 'xgqfrms'
__editor__ = 'vscode'
__version__ = '1.0.1'
__copyright__ = """
  Copyright (c) 2012-2050, xgqfrms; mailto:xgqfrms@xgqfrms.xyz
"""

class Test(object):
  def sum(a, b):
    sum a + b
    print "a+b=" + sum
    return sum

2to3

# coding: utf8

__author__ = 'xgqfrms'
__editor__ = 'vscode'
__version__ = '1.0.1'
__copyright__ = """
  Copyright (c) 2012-2050, xgqfrms; mailto:xgqfrms@xgqfrms.xyz
"""

class Test(object):
  def sum(a, b):
    sum a + b
    print("a+b=", sum)
    return sum

Python 2.x 与 Python 3​​.x 版本区别

  1. print

  2. input

  3. unicode

  4. 除法运算 ///

  5. 异常 as

  6. xrange

  7. 八进制字面量 & 二进制字面量

八进制数必须写成 0o777,原来的形式 0777 不能用了;
二进制必须写成 0b111

新增了一个bin()函数用于将一个整数转换成二进制字串;

  1. 不等运算符

Python 2.x, != 和 <>

Python 3.x, !=

  1. 去掉了repr表达式``

  2. 多个模块被改名(根据PEP8)

10.数据类型 bytes 字节码类型

  1. 打开文件 open

  1. 函数式编程, map、filter 和 reduce

可迭代的对象, next()

https://www.runoob.com/python/python-2x-3x.html

refs

https://pythonconverter.com/

https://docs.python.org/2/library/2to3.html



©xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


posted @ 2020-08-06 12:16  xgqfrms  阅读(264)  评论(0编辑  收藏  举报