Python基本数据类型

六个基本数据类型

1.number

2.string

3.list

4.tuple

5.dict

6.sets

每个基本数据类型都打包成一个类,自带一些常用的成员函数.非常方便使用.

在定义数据类型时前面已经不需要加上数据类型,直接定义变量名.会生成=号后面的相对应的类的对象.

一切皆对象,一切都尽可能simple

1.number

分俩种,带点的和不带点的

在python统称int

可以同时为多个变量赋值, a,b = 12,13

//Python还支持复数,复数可以用a+bj,或者complex(a,b)表示,a和b都是浮点数

2.string

可以使用单引号,也可以用双引号

可以支持字符串截取:变量[头下标:尾下标],称之为切片

    def capitalize(self):  # real signature unknown; restored from __doc__
        """
        S.capitalize() -> str
        *
        返回一个首字母大写,其余都是小写的字符串(无需参数)
        *
        Return a capitalized version of S, i.e. make the first character
        have upper case and the rest lower case.
        """
        return ""

    def casefold(self):  # real signature unknown; restored from __doc__
        """
        S.casefold() -> str
        *
        返回一个全都是小写字母的字符串(无需参数)
        *
        Return a version of S suitable for caseless comparisons.
        """
        return ""


    def center(self, width, fillchar=None):  # real signature unknown; restored from __doc__
        """
        S.center(width[, fillchar]) -> str
        *
        返回一个以fillchar字符填充,左右长度为width.居中的字符串
        width要大于len(str),否则返回原字符串
        默认以' '(空格)填充
        *
        Return S centered in a string of length width. Padding is
        done using the specified fill character (default is a space)
        """
        return ""


    def count(self, sub, start=None, end=None):  # real signature unknown; restored from __doc__
        """
        S.count(sub[, start[, end]]) -> int
        *
        返回一个数值,该数值是变量sub在字符串中出现的次数.没有返回0
        可以选择起始位置start,结束位置end.皆可为None
        *
        Return the number of non-overlapping occurrences of substring sub in
        string S[start:end].  Optional arguments start and end are
        interpreted as in slice notation.
        """
        return 0


    def encode(self, encoding='utf-8', errors='strict'):  # real signature unknown; restored from __doc__
        """
        S.encode(encoding='utf-8', errors='strict') -> bytes
        *
        //返回一个以b开头,字符编码为'utf-8'的字符串,默认设置检查为'strict'
        *
        Encode S using the codec registered for encoding. Default encoding
        is 'utf-8'. errors may be given to set a different error
        handling scheme. Default is 'strict' meaning that encoding errors raise
        a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
        'xmlcharrefreplace' as well as any other name registered with
        codecs.register_error that can handle UnicodeEncodeErrors.
        """
        return b""


    def endswith(self, suffix, start=None, end=None):  # real signature unknown; restored from __doc__
        """
        S.endswith(suffix[, start[, end]]) -> bool
        *
        判断字符串后缀是否是suffix,如果是返回true,其他情况返回false
        可以设置起始位置,结束位置
        *
        Return True if S ends with the specified suffix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        suffix can also be a tuple of strings to try.
        """
        return False


    def expandtabs(self, tabsize=8):  # real signature unknown; restored from __doc__
        """
        S.expandtabs(tabsize=8) -> str
        *
        返回一个设置/t间隔为tabsize的字符串.默认值为8
        *
        Return a copy of S where all tab characters are expanded using spaces.
        If tabsize is not given, a tab size of 8 characters is assumed.
        """
        return ""


    def find(self, sub, start=None, end=None):  # real signature unknown; restored from __doc__
        """
        S.find(sub[, start[, end]]) -> int
        *
        在字符串中查找sub,找到返回下标,找不到返回-1,只能返回第一次出现的位置
        *
        Return the lowest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.

        Return -1 on failure.
        """
        return 0


    def format(self, *args, **kwargs):  # known special case of str.format
        """
        S.format(*args, **kwargs) -> str
        *
        <模板字符串>.format(<逗号分隔的参数>)
        返回一个参数列表中参数填充的模板{}里的字符串
        -----------------------------------------
        name = "我是{},我喜欢{}"
        v = name.format("anqunli","python")
        print(v)
        输入:我是anqunli,我喜欢python
        -----------------------------------------
        *
        Return a formatted version of S, using substitutions from args and kwargs.
        The substitutions are identified by braces ('{' and '}').
        """
        pass


    def format_map(self, mapping):  # real signature unknown; restored from __doc__
        """
        S.format_map(mapping) -> str
        *
        //利用字典
        *
        Return a formatted version of S, using substitutions from mapping.
        The substitutions are identified by braces ('{' and '}').
        """
        return ""


    def index(self, sub, start=None, end=None):  # real signature unknown; restored from __doc__
        """
        S.index(sub[, start[, end]]) -> int
        *
        在源字符串中查找sub,找到返回下标,找不到编译错误
        *
        Return the lowest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.

        Raises ValueError when the substring is not found.
        """
        return 0


    def isalnum(self):  # real signature unknown; restored from __doc__
        """
        S.isalnum() -> bool
        *
        如果源字符串中全都是数字,返回true
        至少有一个字符,则返回false
        *
        Return True if all characters in S are alphanumeric
        and there is at least one character in S, False otherwise.
        """
        return False


    def isalpha(self):  # real signature unknown; restored from __doc__
        """
        S.isalpha() -> bool
        *
        如果源字符串中全都是字母,返回true
        至少有一个数字,则返回false
        *
        Return True if all characters in S are alphabetic
        and there is at least one character in S, False otherwise.
        """
        return False


    def isdecimal(self):  # real signature unknown; restored from __doc__
        """
        S.isdecimal() -> bool
        *
        如果源字符串中全都是十进制数,返回true
        否则返回false
        *
        Return True if there are only decimal characters in S,
        False otherwise.
        """
        return False


    def isdigit(self):  # real signature unknown; restored from __doc__
        """
        S.isdigit() -> bool
        *
        如果源字符串中全都是数字,返回true
        至少有一个字符,则返回false
        *
        Return True if all characters in S are digits
        and there is at least one character in S, False otherwise.
        """
        return False


    def isidentifier(self):  # real signature unknown; restored from __doc__
        """
        S.isidentifier() -> bool
        *
        判断字符串是否为合法的变量名(数字字母下划线,不以数字打头).中文也可以
        合法返回true,否则返回false
        *
        Return True if S is a valid identifier according
        to the language definition.

        Use keyword.iskeyword() to test for reserved identifiers
        such as "def" and "class".
        """
        return False


    def islower(self):  # real signature unknown; restored from __doc__
        """
        S.islower() -> bool
        *
        如果源字符串中全都是小写返回true.否则返回false
        *
        Return True if all cased characters in S are lowercase and there is
        at least one cased character in S, False otherwise.
        """
        return False


    def isnumeric(self):  # real signature unknown; restored from __doc__
        """
        S.isnumeric() -> bool
        *
        如果源字符串中全都是数字返回true,否则返回false
        *
        Return True if there are only numeric characters in S,
        False otherwise.
        """
        return False


    def isprintable(self):  # real signature unknown; restored from __doc__
        """
        S.isprintable() -> bool
        *
        如果源字符串中全都是可打印字符返回true,否则返回false
        /t,/n...为不可打印字符
        *
        Return True if all characters in S are considered
        printable in repr() or S is empty, False otherwise.
        """
        return False


    def isspace(self):  # real signature unknown; restored from __doc__
        """
        S.isspace() -> bool
        *
        如果源字符串中全都是不可见字符返回true,否则返回false
        *
        Return True if all characters in S are whitespace
        and there is at least one character in S, False otherwise.
        """
        return False


    def istitle(self):  # real signature unknown; restored from __doc__
        """
        S.istitle() -> bool
        *
        判断源字符串的首字母是否是大写,其余都是小写.
        如果是返回true,否则返回false
        *
        Return True if S is a titlecased string and there is at least one
        character in S, i.e. upper- and titlecase characters may only
        follow uncased characters and lowercase characters only cased ones.
        Return False otherwise.
        """
        return False


    def isupper(self):  # real signature unknown; restored from __doc__
        """
        S.isupper() -> bool
        *
        如果源字符串都是大写返回true,否则返回false
        *
        Return True if all cased characters in S are uppercase and there is
        at least one cased character in S, False otherwise.
        """
        return False


    def join(self, iterable):  # real signature unknown; restored from __doc__
        """
        S.join(iterable) -> str
        *
        返回一个 将源字符串插入到iterable(字符串序列)中的字符串
        ----------------------------------
        str = '_'
        str2 = ('a','b','c')
        print str.join(str2)
        输出a_b_c
        ----------------------------------
        *
        Return a string which is the concatenation of the strings in the
        iterable.  The separator between elements is S.
        """
        return ""


    def ljust(self, width, fillchar=None):  # real signature unknown; restored from __doc__
        """
        S.ljust(width[, fillchar]) -> str
        *
        返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串
        *
        Return S left-justified in a Unicode string of length width. Padding is
        done using the specified fill character (default is a space).
        """
        return ""


    def lower(self):  # real signature unknown; restored from __doc__
        """
        S.lower() -> str
        *
        转换源字符串中的大写为小写
        *
        Return a copy of the string S converted to lowercase.
        """
        return ""


    def lstrip(self, chars=None):  # real signature unknown; restored from __doc__
        """
        S.lstrip([chars]) -> str
        *
        去除源字符串左边的chars,默认是空格
        *
        Return a copy of the string S with leading whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""


    def maketrans(self, *args, **kwargs):  # real signature unknown
        """
        Return a translation table usable for str.translate().
        *
        创建字符转换表,第一个参数是转换源,第二个参数是转换目标
        --------------------------------------------------
        name = 'anqunli'
        n = 'aeiou'
        n2 = '12345'
        v = name.maketrans(n,n2)
        print(name.translate(v))
        输出为 1nq5nl3
        --------------------------------------------------
        *
        If there is only one argument, it must be a dictionary mapping Unicode
        ordinals (integers) or characters to Unicode ordinals, strings or None.
        Character keys will be then converted to ordinals.
        If there are two arguments, they must be strings of equal length, and
        in the resulting dictionary, each character in x will be mapped to the
        character at the same position in y. If there is a third argument, it
        must be a string, whose characters will be mapped to None in the result.
        """
        pass


    def partition(self, sep):  # real signature unknown; restored from __doc__
        """
        S.partition(sep) -> (head, sep, tail)
        *
        以sep为分隔符,分割源字符串且保留分隔符,
        返回的是一个3元元祖
        *
        Search for the separator sep in S, and return the part before it,
        the separator itself, and the part after it.  If the separator is not
        found, return S and two empty strings.
        """
        pass


    def replace(self, old, new, count=None):  # real signature unknown; restored from __doc__
        """
        S.replace(old, new[, count]) -> str
        *
        把 源字符串 中的 old字串 替换成 new,如果 num 指定,则替换不超过 num 次
        *
        Return a copy of S with all occurrences of substring
        old replaced by new.  If the optional argument count is
        given, only the first count occurrences are replaced.
        """
        return ""


    def rfind(self, sub, start=None, end=None):  # real signature unknown; restored from __doc__
        """
        S.rfind(sub[, start[, end]]) -> int
        *
        从右到左查找源字符串中sub,找到返回下标,找不放返回-1
        *
        Return the highest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.

        Return -1 on failure.
        """
        return 0


    def rindex(self, sub, start=None, end=None):  # real signature unknown; restored from __doc__
        """
        S.rindex(sub[, start[, end]]) -> int
        *
        从右到左查找源字符串中sub,找到返回下标,找不到报错
        *
        Return the highest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.

        Raises ValueError when the substring is not found.
        """
        return 0


    def rjust(self, width, fillchar=None):  # real signature unknown; restored from __doc__
        """
        S.rjust(width[, fillchar]) -> str
        *
        返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串
        *
        Return S right-justified in a string of length width. Padding is
        done using the specified fill character (default is a space).
        """
        return ""


    def rpartition(self, sep):  # real signature unknown; restored from __doc__
        """
        S.rpartition(sep) -> (head, sep, tail)
        *
        从右到左以sep为分隔符,分割源字符串且保留分隔符,
        返回的是一个3元元祖
        *
        Search for the separator sep in S, starting at the end of S, and return
        the part before it, the separator itself, and the part after it.  If the
        separator is not found, return two empty strings and S.
        """
        pass


    def rsplit(self, sep=None, maxsplit=-1):  # real signature unknown; restored from __doc__
        """
        S.rsplit(sep=None, maxsplit=-1) -> list of strings
        *
        从右到左以sep为分隔符,分割源字符串,maxsplit为默认最多切割次数
        返回的是一个列表
        *
        Return a list of the words in S, using sep as the
        delimiter string, starting at the end of the string and
        working to the front.  If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified, any whitespace string
        is a separator.
        """
        return []


    def rstrip(self, chars=None):  # real signature unknown; restored from __doc__
        """
        S.rstrip([chars]) -> str
        *
        删除源字符串末尾的空格
        返回一个包含删除源字符串末尾的空格的字符串的列表
        *
        Return a copy of the string S with trailing whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""


    def split(self, sep=None, maxsplit=-1):  # real signature unknown; restored from __doc__
        """
        S.split(sep=None, maxsplit=-1) -> list of strings
        *
        以sep为分隔符 分割源字符串,maxsplit为默认最多切割次数
        返回的是一个列表
        *
        Return a list of the words in S, using sep as the
        delimiter string.  If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified or is None, any
        whitespace string is a separator and empty strings are
        removed from the result.
        """
        return []


    def splitlines(self, keepends=None):  # real signature unknown; restored from __doc__
        """
        S.splitlines([keepends]) -> list of strings
        *
        在源字符串中按照('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表
        如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。
        -----------------------------------------------
        name = 'a\rnq\nun\nli'
        v = name.splitlines()
        print(v)
        输出为 ['a', 'nq', 'un', 'li']
        -----------------------------------------------
        *
        Return a list of the lines in S, breaking at line boundaries.
        Line breaks are not included in the resulting list unless keepends
        is given and true.
        """
        return []


    def startswith(self, prefix, start=None, end=None):  # real signature unknown; restored from __doc__
        """
        S.startswith(prefix[, start[, end]]) -> bool
        *
        判断源字符串是否以prefix子串结尾,
        如果是返回true,否则返回false
        *
        Return True if S starts with the specified prefix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        prefix can also be a tuple of strings to try.
        """
        return False


    def strip(self, chars=None):  # real signature unknown; restored from __doc__
        """
        S.strip([chars]) -> str
        *
        移除源字符串头尾制定的字符(默认为空格)
        *
        Return a copy of the string S with leading and trailing
        whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""


    def swapcase(self):  # real signature unknown; restored from __doc__
        """
        S.swapcase() -> str
        *
        返回反转源字符串中的大小写的字符串
        *
        Return a copy of S with uppercase characters converted to lowercase
        and vice versa.
        """
        return ""


    def title(self):  # real signature unknown; restored from __doc__
        """
        S.title() -> str
        *
        返回一个首字母是大写其余都是小写的字符串
        *
        Return a titlecased version of S, i.e. words start with title case
        characters, all remaining cased characters have lower case.
        """
        return ""


    def translate(self, table):  # real signature unknown; restored from __doc__
        """
        S.translate(table) -> str
        *//
        根据 str 给出的表(包含 256 个字符)转换 string 的字符,
        要过滤掉的字符放到 del 参数中
        table -- 翻译表,翻译表是通过maketrans方法转换而来。
        deletechars -- 字符串中要过滤的字符列表。
        -----------------------------------------
        from string import maketrans   # 引用 maketrans 函数。

        intab = "aeiou"
        outtab = "12345"
        trantab = maketrans(intab, outtab)

        str = "this is string example....wow!!!";
        print str.translate(trantab);

        输出 th3s 3s str3ng 2x1mpl2....w4w!!!
        ------------------------------------------
        *
        Return a copy of the string S in which each character has been mapped
        through the given translation table. The table must implement
        lookup/indexing via __getitem__, for instance a dictionary or list,
        mapping Unicode ordinals to Unicode ordinals, strings, or None. If
        this operation raises LookupError, the character is left untouched.
        Characters mapped to None are deleted.
        """
        return ""


    def upper(self):  # real signature unknown; restored from __doc__
        """
        S.upper() -> str
        *
        返回一个全是大写的字符串
        *
        Return a copy of S converted to uppercase.
        """
        return ""


    def zfill(self, width):  # real signature unknown; restored from __doc__
        """
        S.zfill(width) -> str
        *
        //返回长度为 width 的字符串,原字符串 string 右对齐,前面填充0
        *
        Pad a numeric string S with zeros on the left, to fill a field
        of the specified width. The string S is never truncated.
        """
        return ""
string

 3.list

list中的元素类型可以不相同,也可以嵌套list

list中的元素可以动态增加和删除,可以用切片

    def append(self, p_object): # real signature unknown; restored from __doc__
        """ L.append(object) -> None -- append object to end """
        *
        在列表末尾添加新的元素
        *
        pass

    def clear(self): # real signature unknown; restored from __doc__
        """ L.clear() -> None -- remove all items from L """
        *
        清空列表
        *
        pass

    def copy(self): # real signature unknown; restored from __doc__
        """ L.copy() -> list -- a shallow copy of L """
        *
        复制一个列表
        *
        return []

    def count(self, value): # real signature unknown; restored from __doc__
        """ L.count(value) -> integer -- return number of occurrences of value """
        *
        计算列表中value元素出现的次数
        *
        return 0

    def extend(self, iterable): # real signature unknown; restored from __doc__
        """ L.extend(iterable) -> None -- extend list by appending elements from the iterable """
        *
        在列表末尾追加另外一个序列
        *
        pass

    def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
        """
        L.index(value, [start, [stop]]) -> integer -- return first index of value.
        Raises ValueError if the value is not present.
        """
        *
        找出value第一次出现的位置,并返回下标,找不到报错
        *
        return 0

    def insert(self, index, p_object): # real signature unknown; restored from __doc__
        """ L.insert(index, object) -- insert object before index """
        *
        将元素插入列表的指定位置
        *
        pass

    def pop(self, index=None): # real signature unknown; restored from __doc__
        """
        L.pop([index]) -> item -- remove and return item at index (default last).
        Raises IndexError if list is empty or index is out of range.
        """
        *
        删除列表中的一个元素(默认为最后一个),并且返回值为该元素,没有则会报错
        *
        pass

    def remove(self, value): # real signature unknown; restored from __doc__
        """
        L.remove(value) -> None -- remove first occurrence of value.
        Raises ValueError if the value is not present.
        """
        *
        删除列表中某个元素的第一个匹配项,没有则会报错
        *
        pass

    def reverse(self): # real signature unknown; restored from __doc__
        """ L.reverse() -- reverse *IN PLACE* """
        *
        反转列表中的元素
        *
        pass

    def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__
        """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
        *
        对列表进行排序,只能是纯数字
        *
        pass
list

4.tuple

元祖,一级元素不可修改.

其余和列表一样

def count(self, value):  # real signature unknown; restored from __doc__
    """ T.count(value) -> integer -- return number of occurrences of value """
    *
    计算value在元祖中出现的次数
    *
    return 0


def index(self, value, start=None, stop=None):  # real signature unknown; restored from __doc__
    """
    T.index(value, [start, [stop]]) -> integer -- return first index of value.
    Raises ValueError if the value is not present.
    """
    *
    找出value在元祖中的位置,返回下标,没有报错
    *
    return 0
tuple

5.dict

元素称为键对值

dict = {"key":type}

通过自定义key值作为下标,取到数据.称为字典

key值只能是不可修改的类型,type可以是任意的

字典本身是动态的,无序.支持嵌套

def clear(self):  # real signature unknown; restored from __doc__
    """ D.clear() -> None.  Remove all items from D. """
    *
    清空字典
    *
    pass


def copy(self):  # real signature unknown; restored from __doc__
    """ D.copy() -> a shallow copy of D """
    *
    拷贝一个字典
    *
    pass


@staticmethod  # known case
def fromkeys(*args, **kwargs):  # real signature unknown
    """ Returns a new dict with keys from iterable and values equal to value. """
    *
    创建一个字典,从参数序列中的元素作为新字典的key值
    *
    pass


def get(self, k, d=None):  # real signature unknown; restored from __doc__
    """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
    *
    作用同dict[key]
    *
    pass


def items(self):  # real signature unknown; restored from __doc__
    """ D.items() -> a set-like object providing a view on D's items """
    *
    返回一个元祖列表元祖
    //以列表返回可遍历的(键, 值)  元组数组(列表转元组)
    *
    pass


def keys(self):  # real signature unknown; restored from __doc__
    """ D.keys() -> a set-like object providing a view on D's keys """
    *
    返回字典所有的key
    *
    pass


def pop(self, k, d=None):  # real signature unknown; restored from __doc__
    """
    D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
    If key is not found, d is returned if given, otherwise KeyError is raised
    """
    *
    删除k对应字典key的键和值,返回key值
    *
    pass


def popitem(self):  # real signature unknown; restored from __doc__
    """
    D.popitem() -> (k, v), remove and return some (key, value) pair as a
    2-tuple; but raise KeyError if D is empty.
    """
    *
    随机返回并删除字典中的一对键和值(一般删除末尾对),如果字典为空则报错
    *
    pass


def setdefault(self, k, d=None):  # real signature unknown; restored from __doc__
    """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
    *
    和get()方法类似, 如果键不存在于字典中,将会添加键并将值设为默认值
    *
    pass


def update(self, E=None, **F):  # known special case of dict.update
    """
    D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
    If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
    If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
    In either case, this is followed by: for k in F:  D[k] = F[k]
    """
    *
    把字典dict2的键和值对追加到dict里
    *
    pass


def values(self):  # real signature unknown; restored from __doc__
    """ D.values() -> an object providing a view on D's values """
    *
    返回字典中所有的value
    *
    pass
dict

6.sets

转载!!
概念:

  集合是一个无序不重复元素的序列。

  基本功能是进行成员关系测试和删除重复元素。

  可以使用大括号{ }或者set()函数创建集合,但是创建一个空集合必须用set()

  创建格式

  ---------------------------------------------------------------
  parame = {value01,value02,...}
  或者
  set(value)
  ---------------------------------------------------------------
用法:

  a = set('abracadabra')

  b = set('alacazam')

  1,差集

    print(a - b)

  2,并集

    print(a | b)

  3,交集

    print(a & b)

  4,反交集

    print(a ^ b)

  5,增

    a.add('666')    增加一个元素

    a.update('abc')  迭代增加 

  6,删

    a.remove     删除一个元素 

    a.pop      随机删除一个元素

    a.clear       清空集合

    del a        删除集合

猜你喜欢

转载自www.cnblogs.com/erhao9767/p/8861017.html