zoukankan      html  css  js  c++  java
  • python2.x与3.x的主要区别笔记

    #coding:utf-8
    '''
    python3.x新的东西


    目录

    • 使用__future__模块
    • print函数
    • 整数除法
    • Unicode
    • xrange
    • 触发异常
    • 处理异常
    • next()函数和.next()方法
    • For循环变量与全局命名空间泄漏
    • 比较无序类型
    • 使用input()解析输入内容


    1,__future__ 模块


    2,print函数
    python2.x:
    print "Hello World" #is acceptable in Python 2
    print x,
    python3.x
    print ("Hello World") # in Python 3, print must be followed by ()
    print(x,end="")
    3,从键盘读取输入
    Python2 中有输入函数两个版本。 input() 和 raw_input()。如果它被包含在引号 '' 或 "",input() 对待接收到的数据作为字符串,否则数据将被视为数字类型。
    Python3 中 raw_input()函数已被弃用。此外,接收到的输入数据总是作为字符串处理

    4,整数除法
    在Python2,两个整数的除法的结果会四舍五入到最接近的整数。如:3/2 其结果将显示 1。 为了获得一个浮点除法,分子或分母必须明确为浮点数。因此无论是 3.0/2 或 3/2.0 或 3.0/2.0 将产生1.5 。
    Python3 计算 3/2 默认结果值为 1.5,这对新手程序员更加直观。

    5,Unicode表示
    Python2 里如果你想将它保存为 Unicode,需要标记为 U 的字符串。
    Python3 中的字符串默认存储为 Unicode。在Python3,我们有个Unicode(UTF-8)字符串和 2 字节类:字节和字节数组。

    6,xrange()函数已被删除

    7,异常
    在 Python3,异常参数应以 'as' 关键字来声明。
    except Myerror, err: # In Python2
    except Myerror as err: #In Python 3

    8,next() 函数和.next()方法
    在Python 2,next() 作为生成器对象的一个方法是允许的。在 Python2,next()函数过度产生器对象遍历也是可以接受的。在Python3,但是,next()函数作为生成器方法来中止并引发AttributeError。
    gen = (letter for letter in 'Hello World') # creates generator object
    next(my_generator) #allowed in Python 2 and Python 3
    my_generator.next() #allowed in Python 2. raises AttributeError in Python 3

    9,2to3实用工具


    '''
    print("%d,%s,%.2f"%(10,"asd",2.3456))
    print(10,end="")

    input(" Press the enter key to exit.") 


    abs(-10)
    min()
    max()

    import math
    math.ceil(0)ceil()方法函数返回x的值上限 - 小于x的最小整数
    math.exp(10)exp()方法返回x的指数幂:e的x次幂
    math.fabs()方法/函数返回x的绝对值。虽然类似于abs()函数,但是两个函数之间有些差异
    abs()是一个内置的函数。 fabs() 在math模块中定义。
    fabs() 函数只适用于浮点和整数。abs() 复数也适用。
    math.floor() 方法返回x的地板 - 最大但不能大于x的整数。
    math.log()方法返回x的自然对数(x>0)。math.log(math.exp(1))==1
    math.log10() 方法返回基数为10的x对数(x>0)。int(math.log10(123456))+1
    math.pow()
    math.sqrt()

    import random
    random.random()


    def cmp(x,y):
    return (x>y)-(x<y)

    >>> math.pi
    3.141592653589793
    >>> math.e
    2.718281828459045
    >>> 

    str.capitalize()
    >>> "asdasd".capitalize()
    'Asdasd'
    >>> 
    str.decode(encoding='UTF-8',errors='strict')
    str.encode(encoding='UTF-8',errors='strict')

    str.find(str, beg=0 end=len(string))
    >>> a="abcdefghijklmn"
    >>> a.find(a)
    0
    >>> a.find("jk",len("jk"))
    9

    islower()方法检查字符串中所有可大小写的字符(字母)是否都为小写字母。

  • 相关阅读:
    【664】日常记录
    【663】dataframe 删掉指定行或者列
    【662】TensorFlow GPU 相关配置
    【661】Python split 指定多个分隔符
    【660】TensorFlow 或者 keras 版本问题
    FFMPEG视音频编解码
    cpplint中filter参数
    升级pip之后出现sys.stderr.write(f“ERROR: {exc}“)
    特征点三角化恢复3D点
    VIO——陀螺仪零偏估计
  • 原文地址:https://www.cnblogs.com/jasonhaven/p/7355000.html
Copyright © 2011-2022 走看看