zoukankan      html  css  js  c++  java
  • 数据类型总结(一)(数字,字符串)

    数据类型总结
    数字
    字符串
    列表
    元组
    字典

    按照存值个数:
    1个:数字,字符串
    多个:列表,元组,字典

    按照可变不可变:
    可变:列表,字典
    不可变:数字,字符串,元组

    按照访问方式:
    直接访问:数字
    索引:字符串,列表,元组==》序列类型seq
    映射:字典

    一.数字

    特性:
    1.只能存放一个值
    2.一经定义,不可更改
    3.直接访问
    分类:整型,长整型(只有python2中才有),浮点,复数

    整型int:年级,年纪,等级,身份证号,qq号,手机号
    level=10
    Python的整型相当于C中的long型,Python中的整数可以用十进制,八进制,十六进制表示。
    >>> 10
    10 --------->默认十进制
    >>> oct(10)
    '012' --------->八进制表示整数时,数值前面要加上一个前缀“0”
    >>> hex(10)
    '0xa' --------->十六进制表示整数时,数字前面要加上前缀0X或0x
    python2.*与python3.*关于整型的区别
    python2.*
    在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647

    在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807
    python3.*整形长度无限制

    整型工厂函数int()

    def bit_length(self): 
            """ 返回表示该数字的时占用的最少位数 """
            """
            int.bit_length() -> int
            
            Number of bits necessary to represent self in binary.
            >>> bin(37)
            '0b100101'
            >>> (37).bit_length()
            """
            return 0
    
        def conjugate(self, *args, **kwargs): # real signature unknown
            """ 返回该复数的共轭复数 """
            """ Returns self, the complex conjugate of any int. """
            pass
    
        def __abs__(self):
            """ 返回绝对值 """
            """ x.__abs__() <==> abs(x) """
            pass
    
        def __add__(self, y):
            """ x.__add__(y) <==> x+y """
            pass
    
        def __and__(self, y):
            """ x.__and__(y) <==> x&y """
            pass
    
        def __cmp__(self, y): 
            """ 比较两个数大小 """
            """ x.__cmp__(y) <==> cmp(x,y) """
            pass
    
        def __coerce__(self, y):
            """ 强制生成一个元组 """ 
            """ x.__coerce__(y) <==> coerce(x, y) """
            pass
    
        def __divmod__(self, y): 
            """ 相除,得到商和余数组成的元组 """ 
            """ x.__divmod__(y) <==> divmod(x, y) """
            pass
    
        def __div__(self, y): 
            """ x.__div__(y) <==> x/y """
            pass
    
        def __float__(self): 
            """ 转换为浮点类型 """ 
            """ x.__float__() <==> float(x) """
            pass
    
        def __floordiv__(self, y): 
            """ x.__floordiv__(y) <==> x//y """
            pass
    
        def __format__(self, *args, **kwargs): # real signature unknown
            pass
    
        def __getattribute__(self, name): 
            """ x.__getattribute__('name') <==> x.name """
            pass
    
        def __getnewargs__(self, *args, **kwargs): # real signature unknown
            """ 内部调用 __new__方法或创建对象时传入参数使用 """ 
            pass
    
        def __hash__(self): 
            """如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。"""
            """ x.__hash__() <==> hash(x) """
            pass
    
        def __hex__(self): 
            """ 返回当前数的 十六进制 表示 """ 
            """ x.__hex__() <==> hex(x) """
            pass
    
        def __index__(self): 
            """ 用于切片,数字无意义 """
            """ x[y:z] <==> x[y.__index__():z.__index__()] """
            pass
    
        def __init__(self, x, base=10): # known special case of int.__init__
            """ 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """ 
            """
            int(x=0) -> int or long
            int(x, base=10) -> int or long
            
            Convert a number or string to an integer, or return 0 if no arguments
            are given.  If x is floating point, the conversion truncates towards zero.
            If x is outside the integer range, the function returns a long instead.
            
            If x is not a number or if base is given, then x must be a string or
            Unicode object representing an integer literal in the given base.  The
            literal can be preceded by '+' or '-' and be surrounded by whitespace.
            The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
            interpret the base from the string as an integer literal.
            >>> int('0b100', base=0)
            # (copied from class doc)
            """
            pass
    
        def __int__(self): 
            """ 转换为整数 """ 
            """ x.__int__() <==> int(x) """
            pass
    
        def __invert__(self): 
            """ x.__invert__() <==> ~x """
            pass
    
        def __long__(self): 
            """ 转换为长整数 """ 
            """ x.__long__() <==> long(x) """
            pass
    
        def __lshift__(self, y): 
            """ x.__lshift__(y) <==> x<<y """
            pass
    
        def __mod__(self, y): 
            """ x.__mod__(y) <==> x%y """
            pass
    
        def __mul__(self, y): 
            """ x.__mul__(y) <==> x*y """
            pass
    
        def __neg__(self): 
            """ x.__neg__() <==> -x """
            pass
    
        @staticmethod # known case of __new__
        def __new__(S, *more): 
            """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
            pass
    
        def __nonzero__(self): 
            """ x.__nonzero__() <==> x != 0 """
            pass
    
        def __oct__(self): 
            """ 返回改值的 八进制 表示 """ 
            """ x.__oct__() <==> oct(x) """
            pass
    
        def __or__(self, y): 
            """ x.__or__(y) <==> x|y """
            pass
    
        def __pos__(self): 
            """ x.__pos__() <==> +x """
            pass
    
        def __pow__(self, y, z=None): 
            """ 幂,次方 """ 
            """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """
            pass
    
        def __radd__(self, y): 
            """ x.__radd__(y) <==> y+x """
            pass
    
        def __rand__(self, y): 
            """ x.__rand__(y) <==> y&x """
            pass
    
        def __rdivmod__(self, y): 
            """ x.__rdivmod__(y) <==> divmod(y, x) """
            pass
    
        def __rdiv__(self, y): 
            """ x.__rdiv__(y) <==> y/x """
            pass
    
        def __repr__(self): 
            """转化为解释器可读取的形式 """
            """ x.__repr__() <==> repr(x) """
            pass
    
        def __str__(self): 
            """转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式"""
            """ x.__str__() <==> str(x) """
            pass
    
        def __rfloordiv__(self, y): 
            """ x.__rfloordiv__(y) <==> y//x """
            pass
    
        def __rlshift__(self, y): 
            """ x.__rlshift__(y) <==> y<<x """
            pass
    
        def __rmod__(self, y): 
            """ x.__rmod__(y) <==> y%x """
            pass
    
        def __rmul__(self, y): 
            """ x.__rmul__(y) <==> y*x """
            pass
    
        def __ror__(self, y): 
            """ x.__ror__(y) <==> y|x """
            pass
    
        def __rpow__(self, x, z=None): 
            """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """
            pass
    
        def __rrshift__(self, y): 
            """ x.__rrshift__(y) <==> y>>x """
            pass
    
        def __rshift__(self, y): 
            """ x.__rshift__(y) <==> x>>y """
            pass
    
        def __rsub__(self, y): 
            """ x.__rsub__(y) <==> y-x """
            pass
    
        def __rtruediv__(self, y): 
            """ x.__rtruediv__(y) <==> y/x """
            pass
    
        def __rxor__(self, y): 
            """ x.__rxor__(y) <==> y^x """
            pass
    
        def __sub__(self, y): 
            """ x.__sub__(y) <==> x-y """
            pass
    
        def __truediv__(self, y): 
            """ x.__truediv__(y) <==> x/y """
            pass
    
        def __trunc__(self, *args, **kwargs): 
            """ 返回数值被截取为整形的值,在整形中无意义 """
            pass
    
        def __xor__(self, y): 
            """ x.__xor__(y) <==> x^y """
            pass
    
        denominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
        """ 分母 = 1 """
        """the denominator of a rational number in lowest terms"""
    
        imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
        """ 虚数,无意义 """
        """the imaginary part of a complex number"""
    
        numerator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
        """ 分子 = 数字大小 """
        """the numerator of a rational number in lowest terms"""
    
        real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
        """ 实属,无意义 """
        """the real part of a complex number"""
    
    int
    Python2.7
    class int(object):
        """
        int(x=0) -> integer
        int(x, base=10) -> integer
        
        Convert a number or string to an integer, or return 0 if no arguments
        are given.  If x is a number, return x.__int__().  For floating point
        numbers, this truncates towards zero.
        
        If x is not a number or if base is given, then x must be a string,
        bytes, or bytearray instance representing an integer literal in the
        given base.  The literal can be preceded by '+' or '-' and be surrounded
        by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
        Base 0 means to interpret the base from the string as an integer literal.
        >>> int('0b100', base=0)
        4
        """
        def bit_length(self): # real signature unknown; restored from __doc__
            """ 返回表示该数字的时占用的最少位数 """
            """
            int.bit_length() -> int
            
            Number of bits necessary to represent self in binary.
            >>> bin(37)
            '0b100101'
            >>> (37).bit_length()
            6
            """
            return 0
    
        def conjugate(self, *args, **kwargs): # real signature unknown
            """ 返回该复数的共轭复数 """
            """ Returns self, the complex conjugate of any int. """
            pass
    
        @classmethod # known case
        def from_bytes(cls, bytes, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 
            """
            int.from_bytes(bytes, byteorder, *, signed=False) -> int
            
            Return the integer represented by the given array of bytes.
            
            The bytes argument must be a bytes-like object (e.g. bytes or bytearray).
            
            The byteorder argument determines the byte order used to represent the
            integer.  If byteorder is 'big', the most significant byte is at the
            beginning of the byte array.  If byteorder is 'little', the most
            significant byte is at the end of the byte array.  To request the native
            byte order of the host system, use `sys.byteorder' as the byte order value.
            
            The signed keyword-only argument indicates whether two's complement is
            used to represent the integer.
            """
            pass
    
        def to_bytes(self, length, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 
            """
            int.to_bytes(length, byteorder, *, signed=False) -> bytes
            
            Return an array of bytes representing an integer.
            
            The integer is represented using length bytes.  An OverflowError is
            raised if the integer is not representable with the given number of
            bytes.
            
            The byteorder argument determines the byte order used to represent the
            integer.  If byteorder is 'big', the most significant byte is at the
            beginning of the byte array.  If byteorder is 'little', the most
            significant byte is at the end of the byte array.  To request the native
            byte order of the host system, use `sys.byteorder' as the byte order value.
            
            The signed keyword-only argument determines whether two's complement is
            used to represent the integer.  If signed is False and a negative integer
            is given, an OverflowError is raised.
            """
            pass
    
        def __abs__(self, *args, **kwargs): # real signature unknown
            """ abs(self) """
            pass
    
        def __add__(self, *args, **kwargs): # real signature unknown
            """ Return self+value. """
            pass
    
        def __and__(self, *args, **kwargs): # real signature unknown
            """ Return self&value. """
            pass
    
        def __bool__(self, *args, **kwargs): # real signature unknown
            """ self != 0 """
            pass
    
        def __ceil__(self, *args, **kwargs): # real signature unknown
            """
            整数返回自己
            如果是小数
             math.ceil(3.1)返回4
            """
            """ Ceiling of an Integral returns itself. """
            pass
    
        def __divmod__(self, *args, **kwargs): # real signature unknown
            """ 相除,得到商和余数组成的元组 """
            """ Return divmod(self, value). """
            pass
    
        def __eq__(self, *args, **kwargs): # real signature unknown
            """ Return self==value. """
            pass
    
        def __float__(self, *args, **kwargs): # real signature unknown
            """ float(self) """
            pass
    
        def __floordiv__(self, *args, **kwargs): # real signature unknown
            """ Return self//value. """
            pass
    
        def __floor__(self, *args, **kwargs): # real signature unknown
            """ Flooring an Integral returns itself. """
            pass
    
        def __format__(self, *args, **kwargs): # real signature unknown
            pass
    
        def __getattribute__(self, *args, **kwargs): # real signature unknown
            """ Return getattr(self, name). """
            pass
    
        def __getnewargs__(self, *args, **kwargs): # real signature unknown
            pass
    
        def __ge__(self, *args, **kwargs): # real signature unknown
            """ Return self>=value. """
            pass
    
        def __gt__(self, *args, **kwargs): # real signature unknown
            """ Return self>value. """
            pass
    
        def __hash__(self, *args, **kwargs): # real signature unknown
            """ Return hash(self). """
            pass
    
        def __index__(self, *args, **kwargs): # real signature unknown
            """ 用于切片,数字无意义 """
            """ Return self converted to an integer, if self is suitable for use as an index into a list. """
            pass
    
        def __init__(self, x, base=10): # known special case of int.__init__
            """ 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """
            """
            int(x=0) -> integer
            int(x, base=10) -> integer
            
            Convert a number or string to an integer, or return 0 if no arguments
            are given.  If x is a number, return x.__int__().  For floating point
            numbers, this truncates towards zero.
            
            If x is not a number or if base is given, then x must be a string,
            bytes, or bytearray instance representing an integer literal in the
            given base.  The literal can be preceded by '+' or '-' and be surrounded
            by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
            Base 0 means to interpret the base from the string as an integer literal.
            >>> int('0b100', base=0)
            4
            # (copied from class doc)
            """
            pass
    
        def __int__(self, *args, **kwargs): # real signature unknown
    
            """ int(self) """
            pass
    
        def __invert__(self, *args, **kwargs): # real signature unknown
            """ ~self """
            pass
    
        def __le__(self, *args, **kwargs): # real signature unknown
            """ Return self<=value. """
            pass
    
        def __lshift__(self, *args, **kwargs): # real signature unknown
            """ Return self<<value. """
            pass
    
        def __lt__(self, *args, **kwargs): # real signature unknown
            """ Return self<value. """
            pass
    
        def __mod__(self, *args, **kwargs): # real signature unknown
            """ Return self%value. """
            pass
    
        def __mul__(self, *args, **kwargs): # real signature unknown
            """ Return self*value. """
            pass
    
        def __neg__(self, *args, **kwargs): # real signature unknown
            """ -self """
            pass
    
        @staticmethod # known case of __new__
        def __new__(*args, **kwargs): # real signature unknown
            """ Create and return a new object.  See help(type) for accurate signature. """
            pass
    
        def __ne__(self, *args, **kwargs): # real signature unknown
            """ Return self!=value. """
            pass
    
        def __or__(self, *args, **kwargs): # real signature unknown
            """ Return self|value. """
            pass
    
        def __pos__(self, *args, **kwargs): # real signature unknown
            """ +self """
            pass
    
        def __pow__(self, *args, **kwargs): # real signature unknown
            """ Return pow(self, value, mod). """
            pass
    
        def __radd__(self, *args, **kwargs): # real signature unknown
            """ Return value+self. """
            pass
    
        def __rand__(self, *args, **kwargs): # real signature unknown
            """ Return value&self. """
            pass
    
        def __rdivmod__(self, *args, **kwargs): # real signature unknown
            """ Return divmod(value, self). """
            pass
    
        def __repr__(self, *args, **kwargs): # real signature unknown
            """ Return repr(self). """
            pass
    
        def __rfloordiv__(self, *args, **kwargs): # real signature unknown
            """ Return value//self. """
            pass
    
        def __rlshift__(self, *args, **kwargs): # real signature unknown
            """ Return value<<self. """
            pass
    
        def __rmod__(self, *args, **kwargs): # real signature unknown
            """ Return value%self. """
            pass
    
        def __rmul__(self, *args, **kwargs): # real signature unknown
            """ Return value*self. """
            pass
    
        def __ror__(self, *args, **kwargs): # real signature unknown
            """ Return value|self. """
            pass
    
        def __round__(self, *args, **kwargs): # real signature unknown
            """
            Rounding an Integral returns itself.
            Rounding with an ndigits argument also returns an integer.
            """
            pass
    
        def __rpow__(self, *args, **kwargs): # real signature unknown
            """ Return pow(value, self, mod). """
            pass
    
        def __rrshift__(self, *args, **kwargs): # real signature unknown
            """ Return value>>self. """
            pass
    
        def __rshift__(self, *args, **kwargs): # real signature unknown
            """ Return self>>value. """
            pass
    
        def __rsub__(self, *args, **kwargs): # real signature unknown
            """ Return value-self. """
            pass
    
        def __rtruediv__(self, *args, **kwargs): # real signature unknown
            """ Return value/self. """
            pass
    
        def __rxor__(self, *args, **kwargs): # real signature unknown
            """ Return value^self. """
            pass
    
        def __sizeof__(self, *args, **kwargs): # real signature unknown
            """ Returns size in memory, in bytes """
            pass
    
        def __str__(self, *args, **kwargs): # real signature unknown
            """ Return str(self). """
            pass
    
        def __sub__(self, *args, **kwargs): # real signature unknown
            """ Return self-value. """
            pass
    
        def __truediv__(self, *args, **kwargs): # real signature unknown
            """ Return self/value. """
            pass
    
        def __trunc__(self, *args, **kwargs): # real signature unknown
            """ Truncating an Integral returns itself. """
            pass
    
        def __xor__(self, *args, **kwargs): # real signature unknown
            """ Return self^value. """
            pass
    
        denominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
        """the denominator of a rational number in lowest terms"""
    
        imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
        """the imaginary part of a complex number"""
    
        numerator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
        """the numerator of a rational number in lowest terms"""
    
        real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
        """the real part of a complex number"""
    Python3.5


    浮点型float:身高,体重,薪资,温度,价格
    height=1.81
    salary=3.3
    Python的浮点数就是数学中的小数,类似C语言中的double。
    在运算中,整数与浮点数运算的结果是浮点数
    浮点数也就是小数,之所以称为浮点数,是因为按照科学记数法表示时,
    一个浮点数的小数点位置是可变的,比如,1.23*109和12.3*108是相等的。
    浮点数可以用数学写法,如1.23,3.14,-9.01,等等。但是对于很大或很小的浮点数,
    就必须用科学计数法表示,把10用e替代,1.23*109就是1.23e9,或者12.3e8,0.000012
    可以写成1.2e-5,等等。
    整数和浮点数在计算机内部存储的方式是不同的,整数运算永远是精确的而浮点数运算则可能会有
    四舍五入的误差。


    复数
    x=1-2j
    print(x.real)
    print(x.imag)

    结果:

    1.0
    -2.0

     

    练习:
    1.现有如下两个变量,请简述 n1 和 n2 是什么关系?
        n1=123
        n2=123
    
    2.现有如下两个变量,请简述 n1 和 n2 是什么关系?
        n1=123456
        n2=123456
    
    3.现有如下两个变量,请简述 n1 和 n2 是什么关系?
        n1=123456
        n2=n1
    
    4.如有一下变量 n1  =  5,请使用 int 的提供的方法,得到该变量最少可以用多少个二进制位表示?

    答案:

    1.
    答:id相同,类型相同,值相同,n1和n2使用同一内存地址
    python内部的优化: -5到157之间的赋值变量都是相同的地址
    2.
    答:id不同,类型相同,值相同,n1和n2使用不同的内存地址
    python内部的优化: -5到157之间的赋值变量都是相同的地址
    3.
    答:id不同,类型相同,值相同,
    n1和n2使用同一内存地址,只是变量名不同
    4.print(n1.bit_length())=3
    最少可以用3个二进制位表示
    View Code

     

    二.字符串

    字符串str:它是一个有序的字符的集合,用于存储和表示基本的文本信息,‘’或“”或‘’‘ ’‘’中间包含的内容称之为字符串,包含在引号(单,双,三)里面,由一串字符组成

    特性:
    1.只能存放一个值
    2.不可变
    3.按照从左到右的顺序定义字符集合,下标从0开始顺序访问,有序
    补充:
      1.字符串的单引号和双引号都无法取消特殊字符的含义,如果想让引号内所有字符均取消特殊意义,在引号前面加r,如name=r'l hf'
      2.unicode字符串与r连用必需在r前面,如name=ur'l hf'

    用途(描述性的数据):姓名,性别,地址,学历,密码:alex3714

    name='egon'

    常用操作

    首先要明确,字符串整体就是一个值,只不过特殊之处在于:
    python中没有字符类型,字符串是由一串字符组成,想取出字符串中
    的字符,也可以按照下标的方式取得

    取值:
    name:取得是字符串整体的那一个值
    name[1]:取得是第二位置的字符

    移除空白 msg.strip()
    分割msg.split('|')
    长度len(msg)
    索引msg[3] msg[-1]
    切片msg[0:5:2] #0 2 4

    Python中的spilt方法只能通过指定的某个字符分割字符串,如果需要指定多个字符,需要用到re模块里的split方法。

    >>> import re  
    >>> a = "Hello world!How are you?My friend.Tom"  
    >>> re.split(" |!|?|.", a)    
    ['Hello', 'world', 'How', 'are', 'you', 'My', 'friend', 'Tom']  
    # name='egon' #name=str('egon')
    # print(type(name))
    
    
    #优先掌握
    #    移除空白strip
    msg='             hello         '
    print(msg)
    print(msg.strip())
    
    msg='***hello*********'
    msg=msg.strip('*')
    print(msg)
    
    print(msg.lstrip('*'))
    print(msg.rstrip('*'))
    
    #用处
    while True:
        name=input('user: ').strip()
        password=input('password: ').strip()
    
        if name == 'egon' and password == '123':
            print('login successfull')
    
    
    
        切分split
    info='root:x:0:0::/root:/bin/bash'
    print(info[0]+info[1]+info[2]+info[3])
    
    user_l=info.split(':')
    print(user_l[0])
    
    msg='hello world egon say hahah'
    print(msg.split()) #默认以空格作为分隔符
    
    cmd='download|xhp.mov|3000'
    cmd_l=cmd.split('|')
    print(cmd_l[1])
    print(cmd_l[0])
    
    print(cmd.split('|',1))#后面的数字代表,切分次数,默认从左往右切分
    
    #用处
    while True:
        cmd=input('>>: ').strip()
        if len(cmd) == 0:continue
        cmd_l=cmd.split()
        print('命令是:%s 命令的参数是:%s' %(cmd_l[0],cmd_l[1]))
    
    
    
    
    #
    #     长度len
    
    # print(len('hell 123'))
    
    #
    #     索引
    
    #
    #     切片:切出子字符串
    # msg='hello world'
    # print(msg[1:3]) #1 2
    # print(msg[1:4]) #1 2 3
    
    
    
    # 掌握部分
    oldboy_age=84
    while True:
        age=input('>>: ').strip()
        if len(age) == 0:continue
        if age.isdigit():
            age=int(age)
        else:
            print('must be int')
    
    
    
    
    
    startswith,endswith
    name='alex_SB'
    print(name.endswith('SB'))
    print(name.startswith('alex'))
    
    
    replace
    name='alex say :i have one tesla,my name is alex'
    print(name.replace('alex','SB',1))
    
    print('my name is %s my age is %s my sex is %s' %('egon',18,'male'))
    print('my name is {} my age is {} my sex is {}'.format('egon',18,'male'))
    print('my name is {0} my age is {1} my sex is {0}:{2}'.format('egon',18,'male'))
    print('my name is {name} my age is {age} my sex is {sex}'.format(
        sex='male',
        age=18,
        name='egon'))
    
    
    name='goee say hello'
    # print(name.find('S',1,3)) #顾头不顾尾,找不到则返回-1不会报错,找到了则显示索引
    # print(name.index('S')) #同上,但是找不到会报错
    
    print(name.count('S',1,5)) #顾头不顾尾,如果不指定范围则查找所有
    
    
    join
    info='root:x:0:0::/root:/bin/bash'
    print(info.split(':'))
    
    l=['root', 'x', '0', '0', '', '/root', '/bin/bash']
    print(':'.join(l))
    
    
    lower,upper
    name='eGon'
    print(name.lower())
    print(name.upper())
    
    
    
    
    
    
    
    
    
    
    
    
    
    #了解部分
    #expandtabs
    name='egon	hello'
    print(name)
    print(name.expandtabs(1))
    
    
    #center,ljust,rjust,zfill
    name='egon'
    # print(name.center(30,'-'))
    print(name.ljust(30,'*'))
    print(name.rjust(30,'*'))
    print(name.zfill(50)) #用0填充
    
    
    #captalize,swapcase,title
    name='eGon'
    print(name.capitalize()) #首字母大写,其余部分小写
    print(name.swapcase()) #大小写翻转
    msg='egon say hi'
    print(msg.title()) #每个单词的首字母大写
    
    
    
    
    
    
    #在python3中
    num0='4'
    num1=b'4' #bytes
    num2=u'4' #unicode,python3中无需加u就是unicode
    num3='' #中文数字
    num4='' #罗马数字
    
    
    #isdigt:str,bytes,unicode
    print(num0.isdigit())
    print(num1.isdigit())
    print(num2.isdigit())
    print(num3.isdigit())
    print(num4.isdigit())
    
    #isdecimal:str,unicode
    num0='4'
    num1=b'4' #bytes
    num2=u'4' #unicode,python3中无需加u就是unicode
    num3='' #中文数字
    num4='' #罗马数字
    print(num0.isdecimal())
    # print(num1.)
    print(num2.isdecimal())
    print(num3.isdecimal())
    print(num4.isdecimal())
    
    #isnumeric:str,unicode,中文,罗马
    num0='4'
    num1=b'4' #bytes
    num2=u'4' #unicode,python3中无需加u就是unicode
    num3='' #中文数字
    num4='' #罗马数字
    
    print(num0.isnumeric())
    # print(num1)
    print(num2.isnumeric())
    print(num3.isnumeric())
    print(num4.isnumeric())
    
    
    
    
    #is其他
    name='egon123'
    print(name.isalnum()) #字符串由字母和数字组成
    name='asdfasdfa sdf'
    print(name.isalpha()) #字符串只由字母组成
    #
    
    name='asdfor123'
    print(name.isidentifier())
    name='egGon'
    print(name.islower())
    print(name.isupper())
    print(name.isspace())
    name='Egon say'
    print(name.istitle())
    View Code
    # n=1
    #
    # f=1.3
    #
    # print(type(n))
    # print(type(f))
    
    # print(1.3e-3)
    # print(1.3e3)
    
    #3
    
    # print(bin(10))
    #
    # print(oct(10))
    # # 0-9 a b c d e f
    # print(hex(10))
    
    
    
    #数字类型的特点:
    # 1.只能存放一个值
    #
    # 2.一经定义,不可更改
    #
    # 3.直接访问
    # x=10123123123
    # print(id(x))
    # x=11
    # print(id(11))
    
    
    #字符串类型:引号包含的都是字符串类型
    #需要掌握的常用操作:
    '''
    msg='hello'
    移除空白 msg.strip()
    分割msg.split('|')
    长度len(msg)
    索引msg[3] msg[-1]
    切片msg[0:5:2]  #0  2  4
    
    '''
    
    
    # s='hello world'
    # s1="hello world"
    # s2="""hello world"""
    # s3='''hello world'''
    # print(type(s))
    # print(type(s1))
    # print(type(s2))
    # print(type(s3))
    
    
    x='*****egon********'
    
    # x=x.strip()
    # print(x)
    # print(x.strip('*'))
    
    #首字母大写
    # x='hello'
    # print(x.capitalize())
    
    #所有字母大写
    # x='hello'
    # print(x.upper())
    
    # #居中显示
    # x='hello'
    # print(x.center(30,'#'))
    
    #统计某个字符的长度,空格也算字符
    # x='hel lo love'
    # print(x.count('l'))
    # print(x.count('l',0,4)) # 0 1 2 3
    
    
    #判断开头,结尾的字符
    # x='hello '
    # print(x.endswith(' '))
    # print(x.startswith())
    
    #查找
    # x='hello '
    # print(x.find('e'))
    # print(x.find('l'))
    
    #格式化字符串
    # msg='Name:{},age:{},sex:{}'
    # print(msg) #Name:{},age:{},sex:{}
    # print(msg.format('egon',18,'male'))
    
    
    # msg='Name:{0},age:{1},sex:{0}'
    # print(msg.format('aaaaaaaaaaaaaaaaa','bbbbbbbbbbbbbb'))
    
    
    
    # msg='Name:{x},age:{y},sex:{z}'
    # print(msg.format(y=18,x='egon',z='male'))
    
    
    
    x='hello world'
    # print(x[0])
    # print(x[4])
    # print(x[5])
    # print(x[100]) #报错
    
    # print(x[-1])
    # print(x[-3])
    # print(x[1:3])
    # print(x[1:5:2])
    
    
    # x='hello'
    # print(x.index('o'))
    # print(x[4])
    # print(x[x.index('o')])
    
    # x='123'
    # print(x.isdigit())
    #
    # age=input('age: ')
    # if age.isdigit():
    #     new_age=int(age)
    #     print(new_age,type(new_age))
    
    
    
    msg='hello alex'
    # print(msg.replace('x','X'))
    # print(msg.replace('alex','SB'))
    # print(msg.replace('l','A'))
    # print(msg.replace('l','A',1))
    # print(msg.replace('l','A',2))
    
    
    #补充
    # x='a' #x=str('a')
    # str.replace()
    
    
    # x='hello          world alex SB'
    # x='root:x:0:0::/root:/bin/bash'
    # print(x.split(':'))
    
    
    
    
    
    # x='hello'
    # # print(x.upper())
    # x='H'
    # print(x.isupper())
    x='HELLO'
    # print(x.islower())
    # print(x.lower())
    
    
    x='     '
    # print(x.isspace())
    
    msg='Hello'
    msg='hEEEE'
    # print(msg.istitle())
    
    
    # x='abc'
    # print(x.ljust(10,'*'))
    # print(x.rjust(10,'*'))
    
    # x='Ab'
    # print(x.swapcase())
    #
    # x='hello'
    # print(x.title())
    View Code
    #strip
    name='*egon**'
    print(name.strip('*'))
    print(name.lstrip('*'))
    print(name.rstrip('*'))
    
    #startswith,endswith
    name='alex_SB'
    print(name.endswith('SB'))
    print(name.startswith('alex'))
    
    #replace
    name='alex say :i have one tesla,my name is alex'
    print(name.replace('alex','SB',1))
    
    #format的三种玩法
    res='{} {} {}'.format('egon',18,'male')
    res='{1} {0} {1}'.format('egon',18,'male')
    res='{name} {age} {sex}'.format(sex='male',name='egon',age=18)
    
    #find,rfind,index,rindex,count
    name='egon say hello'
    print(name.find('o',1,3)) #顾头不顾尾,找不到则返回-1不会报错,找到了则显示索引
    # print(name.index('e',2,4)) #同上,但是找不到会报错
    print(name.count('e',1,3)) #顾头不顾尾,如果不指定范围则查找所有
    
    
    #split
    name='root:x:0:0::/root:/bin/bash'
    print(name.split(':')) #默认分隔符为空格
    name='C:/a/b/c/d.txt' #只想拿到顶级目录
    print(name.split('/',1))
    
    name='a|b|c'
    print(name.rsplit('|',1)) #从右开始切分
    
    
    #join
    tag=' '
    print(tag.join(['egon','say','hello','world'])) #可迭代对象必须都是字符串
    
    #center,ljust,rjust,zfill
    name='egon'
    print(name.center(30,'-'))
    print(name.ljust(30,'*'))
    print(name.rjust(30,'*'))
    print(name.zfill(50)) #用0填充
    
    
    #expandtabs
    name='egon	hello'
    print(name)
    print(name.expandtabs(1))
    
    #lower,upper
    name='egon'
    print(name.lower())
    print(name.upper())
    
    
    #captalize,swapcase,title
    print(name.capitalize()) #首字母大写
    print(name.swapcase()) #大小写翻转
    msg='egon say hi'
    print(msg.title()) #每个单词的首字母大写
    
    #is数字系列
    #在python3中
    num1=b'4' #bytes
    num2=u'4' #unicode,python3中无需加u就是unicode
    num3='' #中文数字
    num4='' #罗马数字
    
    #isdigt:bytes,unicode
    print(num1.isdigit()) #True
    print(num2.isdigit()) #True
    print(num3.isdigit()) #False
    print(num4.isdigit()) #False
    
    
    #isdecimal:uncicode
    #bytes类型无isdecimal方法
    print(num2.isdecimal()) #True
    print(num3.isdecimal()) #False
    print(num4.isdecimal()) #False
    
    #isnumberic:unicode,中文数字,罗马数字
    #bytes类型无isnumberic方法
    print(num2.isnumeric()) #True
    print(num3.isnumeric()) #True
    print(num4.isnumeric()) #True
    
    
    #三者不能判断浮点数
    num5='4.3'
    print(num5.isdigit()) 
    print(num5.isdecimal())
    print(num5.isnumeric())
    '''
    总结:
        最常用的是isdigit,可以判断bytes和unicode类型,这也是最常见的数字应用场景
        如果要判断中文数字或罗马数字,则需要用到isnumeric
    '''
    
    #is其他
    print('===>')
    name='egon123'
    print(name.isalnum()) #字符串由字母和数字组成
    print(name.isalpha()) #字符串只由字母组成
    
    print(name.isidentifier())
    print(name.islower())
    print(name.isupper())
    print(name.isspace())
    print(name.istitle())
    View Code

    练习

    # 写代码,有如下变量,请按照要求实现每个功能 (共6分,每小题各0.5分)
    name = " aleX"
    # 1)    移除 name 变量对应的值两边的空格,并输出处理结果
    # 2)    判断 name 变量对应的值是否以 "al" 开头,并输出结果# 3)    判断 name 变量对应的值是否以 "X" 结尾,并输出结果# 4)    将 name 变量对应的值中的 “l” 替换为 “p”,并输出结果
    # 5)    将 name 变量对应的值根据 “l” 分割,并输出结果。
    # 6)    将 name 变量对应的值变大写,并输出结果# 7)    将 name 变量对应的值变小写,并输出结果# 8)    请输出 name 变量对应的值的第 2 个字符?
    # 9)    请输出 name 变量对应的值的前 3 个字符?
    # 10)    请输出 name 变量对应的值的后 2 个字符?# 11)    请输出 name 变量对应的值中 “e” 所在索引位置?# 12)    获取子序列,去掉最后一个字符。如: oldboy 则获取 oldbo。


    # 写代码,有如下变量,请按照要求实现每个功能 (共6分,每小题各0.5分)
    name = " aleX"
    # 1)    移除 name 变量对应的值两边的空格,并输出处理结果
    name = ' aleX'
    a=name.strip()
    print(a)
    
    # 2)    判断 name 变量对应的值是否以 "al" 开头,并输出结果
    name=' aleX'
    if name.startswith(name):
        print(name)
    else:
        print('no')
    
    # 3)    判断 name 变量对应的值是否以 "X" 结尾,并输出结果
    name=' aleX'
    if name.endswith(name):
        print(name)
    else:
        print('no')
    
    # 4)    将 name 变量对应的值中的 “l” 替换为 “p”,并输出结果
    name=' aleX'
    print(name.replace('l','p'))
    
    # 5)    将 name 变量对应的值根据 “l” 分割,并输出结果。
    name=' aleX'
    print(name.split('l'))
    
    # 6)    将 name 变量对应的值变大写,并输出结果
    name=' aleX'
    print(name.upper())
    
    # 7)    将 name 变量对应的值变小写,并输出结果
    name=' aleX'
    print(name.lower())
    
    # 8)    请输出 name 变量对应的值的第 2 个字符?
    name=' aleX'
    print(name[1])
    
    # 9)    请输出 name 变量对应的值的前 3 个字符?
    name=' aleX'
    print(name[:3])
    
    # 10)    请输出 name 变量对应的值的后 2 个字符?
    name=' aleX'
    print(name[-2:])
    
    # 11)    请输出 name 变量对应的值中 “e” 所在索引位置?
    name=' aleX'
    print(name.index('e'))
    
    # 12)    获取子序列,去掉最后一个字符。如: oldboy 则获取 oldbo。
    name=' aleX'
    a=name[:-1]
    print(a)
    View Code
    
    
    


  • 相关阅读:
    12迭代器
    11(2)Vector(向量)
    11(1) LinkList ---链表
    11集合(Collection<E>) Arraylist
    10异常
    乘法计算过程的模拟
    10 Date详解
    详细的OA系统学习
    8 math类
    Java开发中的23种设计模式详解
  • 原文地址:https://www.cnblogs.com/huchong/p/7224736.html
Copyright © 2011-2022 走看看